Program to loop on every character in string in C++

C++Server Side ProgrammingProgramming

Here in this program we will see how to iterate through each characters of a string in C++. To loop on each character, we can use loops starting from 0 to (string length – 1). For accessing the character we can either use subscript operator "[ ]" or at() function of string object.

Input: A string “Hello World”
Output: “Hello World”

Algorithm

Step 1: Get the string
Step 2: Use R before string to make it raw string
Step 3: End

Example Code

 Live Demo

#include<iostream>
using namespace std;
main() {
   string my_str = "Hello World";
   for(int i = 0; i<my_str.length(); i++) {
      cout << my_str.at(i) << endl; //get character at position i
   }
}

Output

H
e
l
l
o

W
o
r
l
d
raja
Published on 28-Mar-2019 08:56:58
Advertisements