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



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

#include<iostream>
using namespace std;
int 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
   }
   return 0;
}

Output

H
e
l
l
o

W
o
r
l
d
Updated on: 2024-12-05T13:28:04+05:30

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements