319

How would I do a for loop on every character in string in C++?

4
  • 11
    What kind of string? C-string, or std::string? Commented Feb 24, 2012 at 21:20
  • It's read in a from a text file, so I'm assuming std:: Commented Feb 24, 2012 at 21:22
  • 4
    What kind of character? char, Unicode code point, extended grapheme cluster? Commented Feb 24, 2012 at 21:26
  • Possible duplicate of How can I iterate through a string and also know the index (current position)?. Don't worry about the index part in the answers. Commented Oct 12, 2014 at 4:55

10 Answers 10

557
  1. Looping through the characters of a std::string, using a range-based for loop (it's from C++11, already supported in recent releases of GCC, clang, and the VC11 beta):

    std::string str = ???;
    for(char& c : str) {
        do_things_with(c);
    }
    
  2. Looping through the characters of a std::string with iterators:

    std::string str = ???;
    for(std::string::iterator it = str.begin(); it != str.end(); ++it) {
        do_things_with(*it);
    }
    
  3. Looping through the characters of a std::string with an old-fashioned for-loop:

    std::string str = ???;
    for(std::string::size_type i = 0; i < str.size(); ++i) {
        do_things_with(str[i]);
    }
    
  4. Looping through the characters of a null-terminated character array:

    char* str = ???;
    for(char* it = str; *it; ++it) {
        do_things_with(*it);
    }
    
Sign up to request clarification or add additional context in comments.

15 Comments

@Robinson: That's a faulty assumption. A very faulty assumption. Also, "character" has so many different meanings, it's best to strictly avoid the term.
Well, OK, it has no encoding, however given the ubiquity of utf8 now (especially on the web) and the fact that one might want a single consistent encoding throughout a pipeline or application, for the basis of this discussion my std::strings are all utf8 :p.
@Robinson: And all of mine are treated as encoding-less because I am not programming in a user-facing domain (that is, there are no strings destined to be rendered to humans). If you want to talk about character encodings, you need to talk about a higher-level abstraction on top of std::string, which is just a series of bytes.
also, cases 2 and 3 are good example of where you can/should use "auto"
char& produces unnecessary dereferencings, which involves more than a single byte of char. Use const char instead.
|
40

A for loop can be implemented like this:

string str("HELLO");
for (int i = 0; i < str.size(); i++){
    cout << str[i];
}

This will print the string character by character. str[i] returns character at index i.

If it is a character array:

char str[6] = "hello";
for (int i = 0; str[i] != '\0'; i++){
    cout << str[i];
}

Basically above two are two type of strings supported by c++. The second is called c string and the first is called std string or(c++ string).I would suggest use c++ string,much Easy to handle.

Comments

31

In modern C++:

std::string s("Hello world");

for (char & c : s)
{
    std::cout << "One character: " << c << "\n";
    c = '*';
}

In C++98/03:

for (std::string::iterator it = s.begin(), end = s.end(); it != end; ++it)
{
    std::cout << "One character: " << *it << "\n";
    *it = '*';
}

For read-only iteration, you can use std::string::const_iterator in C++98, and for (char const & c : s) or just for (char c : s) in C++11.

3 Comments

Here's a couple options for compilers with partial C++11 support: pastebin.com/LBULsn76
@BenjaminLindley: Thanks! auto is always a good idea. When using it, the distinction between begin() and cbegin() becomes relevant.
what is the role of the reference in char here (char & c)? Is it just to allow the modification of the character value in the case it's needed?
17

Here is another way of doing it, using the standard algorithm.

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
   std::string name = "some string";
   std::for_each(name.begin(), name.end(), [] (char c) {
      std::cout << c;
   });
}

2 Comments

We have the year 2018 so this should be the correct answer.
One could also use std::all_of, std::any_of, etc. according to their needs en.cppreference.com/w/cpp/algorithm/all_any_none_of
8
const char* str = "abcde";
int len = strlen(str);
for (int i = 0; i < len; i++)
{
    char chr = str[i];
    //do something....
}

4 Comments

(Outdated comment, that is still probably relevant for the OP:) It is not considered good form to use strlen in the loop condition, as it requires an O(n) operation on the string for each iteration, making the entire loop O(n^2) in the size of the string. strlen in the loop condition can be called for if the string changes during the loop, but should be reserved for the cases where it is actually required.
@MagnusHoff: Yup, Schlemiel the Painter rears his ugly head again.
I've edited my answer. Magnus you're right, oops been using foreach in c# for the last couple of years ;)
You should however still use strlen() outside the loop in preference to testing for null in every iteration.
7

I don't see any examples using a range based for loop with a "c string".

char cs[] = "This is a c string\u0031 \x32 3";

// range based for loop does not print '\n'
for (char& c : cs) {
    printf("%c", c);
}

not related but int array example

int ia[] = {1,2,3,4,5,6};

for (int& i : ia) {
    printf("%d", i);
}

Comments

2
for (int x = 0; x < yourString.size();x++){
        if (yourString[x] == 'a'){
            //Do Something
        }
        if (yourString[x] == 'b'){
            //Do Something
        }
        if (yourString[x] == 'c'){
            //Do Something
        }
        //...........
    }

A String is basically an array of characters, therefore you can specify the index to get the character. If you don't know the index, then you can loop through it like the above code, but when you're making a comparison, make sure you use single quotes (which specifies a character).

Other than that, the above code is self explanatory.

Comments

1

For C-string (char []) you should do something like this:

char mystring[] = "My String";
int size = strlen(mystring);
int i;
for(i = 0; i < size; i++) {
    char c = mystring[i];
}

For std::string you can use str.size() to get its size and iterate like the example , or could use an iterator:

std::string mystring = "My String";
std::string::iterator it;
for(it = mystring.begin(); it != mystring.end(); it++) {
    char c = *it;
}

Comments

1

You can use the size() method to get the lenght of the string and the square bracket operator to access each individual character.

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

int main()
{
   string s;
   cin >> s;
   int length = s.size();
   for(int i = 0; i < length; i++)
   {
      process(s[i]);
   }
}

Comments

0

you can get every char in a string by using the at function of string library, like i did it like this

string words;
    for (unsigned int i = 0; i < words.length(); i++)
        {
            if (words.at(i) == ' ')
            {
                spacecounter++;    // to count all the spaces in a string
                if (words.at(i + 1) == ' ')
                {
                    i += 1;
                }

this is just a segment of my code but the point is you can access characters by stringname.at(index)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.