How to iterate over characters of a string in C++

A string is a continuous sequence of characters. In order to perform some operations on the strings we iterate over the characters of a string. In this article, we are going to discuss some of the simple ways to traverse or iterate a string.

Since strings are similar to arrays of characters, we can simply iterate over characters using a for loop and the length of a string. We can find the length of a string in different ways, here we are going to use length() function on the string for finding the length of the input string.

Different ways to iterate over characters of a string :

  • Using a simple for loop
  • Using iterator
  • Using auto keyword

Iterate over characters of a string using simple for loop

For the first approach, we will consider a string ‘s‘ of length ‘n‘. Where n = str.length() and use a for loop to iterate over every character of a string from the 0th index until the nth index. Below is the code to do so.

#include <iostream>
using namespace std;
int main() {
    string s = "CodeSpeedy";
    int n = s.length();
    for(int i = 0; i < n; i++)
    {
        cout<<s[i]<<" ";
    }
    return 0;
}

Output  :

C o d e S p e e d y

Using iterator

In the second approach, we will be using an iterator “i“, which will store the address of a character of the string s. So in for loop, we iterate i from the beginning of the string s i.e, i = s.begin() and loop until the end of the string i.e., i != s.end(). While printing the characters we will be using pointer “*” since “i” stores the address of characters.

#include <iostream>
using namespace std;
int main() {
    string s = "CodeSpeedy";
    string :: iterator i;
    for(i = s.begin(); i != s.end(); i++)
    {
        cout<<*i<<" ";
    }
    return 0;
}

Output :

C o d e S p e e d y

Auto keyword to iterate over characters of a string in C++

The “auto” keyword is generally used to traverse over the container elements in order to eliminate long initializations. Since it has an automatic deduction of data type its most frequently used for traversal. Below is the code to traverse or iterate over the characters of a string using the auto keyword.

#include <iostream>
using namespace std;
int main() {
    string s = "CodeSpeedy";
    for(auto c : s)
    {
        cout<< c <<" ";
    }
    return 0;
}

Output : 

C o d e S p e e d y

There are some other approaches for string traversal. Hope you have understood the discussion.

Leave a Reply

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