For every character in string

510,964

Solution 1

  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);
    }
    

Solution 2

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.

Solution 3

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.

Solution 4

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;
   });
}

Solution 5

const char* str = "abcde";
int len = strlen(str);
for (int i = 0; i < len; i++)
{
    char chr = str[i];
    //do something....
}
Share:
510,964

Related videos on Youtube

Jack Wilsdon
Author by

Jack Wilsdon

Updated on July 08, 2022

Comments

  • Jack Wilsdon
    Jack Wilsdon almost 2 years

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

    • Mysticial
      Mysticial about 12 years
      What kind of string? C-string, or std::string?
    • Jack Wilsdon
      Jack Wilsdon about 12 years
      It's read in a from a text file, so I'm assuming std::
    • Philipp
      Philipp about 12 years
      What kind of character? char, Unicode code point, extended grapheme cluster?
    • jww
      jww over 9 years
      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.
  • mrivard
    mrivard about 12 years
    (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.
  • Drew Delano
    Drew Delano about 12 years
    @MagnusHoff: Yup, Schlemiel the Painter rears his ugly head again.
  • demoncodemonkey
    demoncodemonkey about 12 years
    I've edited my answer. Magnus you're right, oops been using foreach in c# for the last couple of years ;)
  • Benjamin Lindley
    Benjamin Lindley about 12 years
    Here's a couple options for compilers with partial C++11 support: pastebin.com/LBULsn76
  • Kerrek SB
    Kerrek SB about 12 years
    @BenjaminLindley: Thanks! auto is always a good idea. When using it, the distinction between begin() and cbegin() becomes relevant.
  • Robinson
    Robinson almost 10 years
    This does confuse me somewhat, given std::string is UTF8 (assumed to be), so encoding is possibly variable length. Are you iterating through the bytes in the string or the characters here?
  • R. Martinho Fernandes
    R. Martinho Fernandes almost 10 years
    std::string is (defined to be) a null-terminated sequence of char objects.
  • Puppy
    Puppy almost 10 years
    @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.
  • Robinson
    Robinson almost 10 years
    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.
  • Lightness Races in Orbit
    Lightness Races in Orbit almost 10 years
    @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.
  • LunaticSoul
    LunaticSoul almost 9 years
    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?
  • Sam Eaton
    Sam Eaton over 8 years
    Is it possible to peek at the next character with your #1 example?
  • galois
    galois about 8 years
    also, cases 2 and 3 are good example of where you can/should use "auto"
  • Florian Winter
    Florian Winter over 6 years
    This does NOT loop over each character of the string. It loops over each byte of the representation of the string as a sequence of bytes. However, a character may consist of a sequence of multiple bytes.
  • R. Martinho Fernandes
    R. Martinho Fernandes over 6 years
    @FlorianWinter in C++, "each byte of the representation of the string as a sequence of bytes" is called a character eel.is/c++draft/basic.fundamental#1. (Yes, it sucks)
  • rwst
    rwst almost 6 years
    We have the year 2018 so this should be the correct answer.
  • Gusev Slava
    Gusev Slava over 5 years
    Is it possible to use auto& c in case 1 ?
  • mckenzm
    mckenzm almost 5 years
    We should speak of bytes, rather than characters, it is very hard to fit multi byte unicode into 8-N-1 say, and we may have to from time to time.
  • mckenzm
    mckenzm almost 5 years
    You should however still use strlen() outside the loop in preference to testing for null in every iteration.
  • O-9
    O-9 about 4 years
    (1.) For const strings, const must be used for single char: for(const char& c : word)
  • Константин Ван
    Константин Ван over 3 years
    char& produces unnecessary dereferencings, which involves more than a single byte of char. Use const char instead.
  • DeepBlue
    DeepBlue about 3 years
    clang-tidy -modernize-loop-convert discourages you from using the old fashioned option (3) in favor of forrange option (1)
  • aurelia
    aurelia almost 3 years
    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