Iterate over characters of a string in C++ (original) (raw)

Last Updated : 17 Jan, 2026

Given a string **str of length **N, the task is to traverse the string and print all the characters of the given string.

**For Example:

C++ `

#include <bits/stdc++.h> using namespace std;

int main() { string str = "GeeksforGeeks";

int N = str.length();
for (int i = 0; i < N; i++) {
    cout<< str[i]<< " ";
}

}

`

Output

G e e k s f o r G e e k s

**Explanation: The program iterates over the string str using a for loop from index 0 to N - 1, where N is the length of the string. In each iteration, the character at index i (str[i]) is accessed and printed followed by a space.

Let's look at some other ways of doing it in C++:

1. Using "auto" keyword

The string can be traversed using auto iterator.

C++ `

#include <bits/stdc++.h> using namespace std;

int main(){ string str = "GeeksforGeeks"; int N = str.length(); for (auto &ch : str) { cout<< ch<< " "; } return 0; }

`

Output

G e e k s f o r G e e k s

**Explanation:

2. Using Iterator

The string can be traversed using iterator.

C++ `

#include <bits/stdc++.h> using namespace std;

int main(){ string str = "GeeksforGeeks"; int N = str.length();

string::iterator it;
for (it = str.begin(); it != str.end(); it++) {
    cout << *it << " ";
}

return 0;

}

`

Output

G e e k s f o r G e e k s

**Explanation: