Ways to Iterate over characters of a string in C++ coding

 

Given a string str of size N, the duty is to traverse the string and print all of the characters of the given string.

Examples:

Input: str = “GeeksforGeeks”
Output: G e e ok s f o r G e e ok s

Input: str = “Coder”
Output: C o d e r

 

Naive Approach: The easiest ways to resolve this drawback is to iterate a loop  on vary [0, N – 1], the place N denotes the size of the string, using variable i and print the worth of str[i].

Below is the implementation of the above strategy:

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()

Output:

G e e ok s f o r G e e ok s

Time Complexity: O(N)
Auxiliary Space: O(1)

Auto key phrase – based mostly Approach: The string might be traversed using auto iterator.

Below is the implementation of the above strategy:

C++

 

#include <bits/stdc++.h>

using namespace std;

 

void TraverseString(string &str, int N)

{

    

    for (auto &ch : str) {

 

        

        cout<< ch<< " ";

    }

}

int main()

Output:

G e e ok s f o r G e e ok s

Time Complexity: O(N)
Auxiliary Space: O(1)

Iterator – based mostly Approach: The string might be traversed using iterator.

Below is the implementation of the above strategy:

C++

 

#include <bits/stdc++.h>

using namespace std;

 

void TraverseString(string &str, int N)

{

     

    

    

    string:: iterator it;

     

    

    for (it = str.start(); it != str.finish();

                                   it++) {

        

        cout<< *it<< " ";

    }

}

 

int main()

Output:

G e e ok s f o r G e e ok s

Time Complexity: O(N)
Auxiliary Space: O(1)

 

Add a Comment

Your email address will not be published. Required fields are marked *