Iterate over characters of a string in C++
Last Updated :
24 Nov, 2020
Given a string str of length N, the task is to traverse the string and print all the characters of the given string.
Examples:
Input: str = “GeeksforGeeks”
Output: G e e k s f o r G e e k s
Input: str = “Coder”
Output: C o d e r
Naive Approach: The simplest approach to solve this problem is to iterate a loop over the range [0, N – 1], where N denotes the length of the string, using variable i and print the value of str[i].
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void TraverseString(string &str, int N)
{
for ( int i = 0; i < N; i++) {
cout<< str[i]<< " " ;
}
}
int main()
{
string str = "GeeksforGeeks" ;
int N = str.length();
TraverseString(str, N);
}
|
Output:
G e e k s f o r G e e k s
Time Complexity: O(N)
Auxiliary Space: O(1)
Auto keyword – based Approach: The string can be traversed using auto iterator.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void TraverseString(string &str, int N)
{
for ( auto &ch : str) {
cout<< ch<< " " ;
}
}
int main()
{
string str = "GeeksforGeeks" ;
int N = str.length();
TraverseString(str, N);
}
|
Output:
G e e k s f o r G e e k s
Time Complexity: O(N)
Auxiliary Space: O(1)
Iterator – based Approach: The string can be traversed using iterator.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void TraverseString(string &str, int N)
{
string:: iterator it;
for (it = str.begin(); it != str.end();
it++) {
cout<< *it<< " " ;
}
}
int main()
{
string str = "GeeksforGeeks" ;
int N = str.length();
TraverseString(str, N);
}
|
Output:
G e e k s f o r G e e k s
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...