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:
#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.
#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:
- The string str stores "GeeksforGeeks".
- "auto" automatically detects the type of ch as char.
- "auto &ch" means each character is accessed by reference from the string.
- The range-based loop prints every character of the string with a space.
2. Using Iterator
The string can be traversed using iterator.
#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:
- "string::iterator it", declares an iterator that points to characters in the string.
- "str.begin()" returns an iterator to the first character of the string.
- "str.end()" returns an iterator to the position after the last character.
- The for loop moves the iterator from start to end using "it++".
- "*it" dereferences the iterator to access and print each character.