如何在c++中对字符串中的每个字符进行for循环?


当前回答

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
        }
        //...........
    }

String基本上是一个字符数组,因此您可以指定索引来获取字符。如果您不知道索引,那么您可以像上面的代码一样对其进行循环,但是当您进行比较时,请确保使用单引号(它指定一个字符)。

除此之外,上面的代码是自解释的。

其他回答

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); } 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); } 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]); } Looping through the characters of a null-terminated character array: char* str = ???; for(char* it = str; *it; ++it) { do_things_with(*it); }

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

这是另一种方法,使用标准算法。

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

在现代c++中:

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

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

在 C++98/03 中:

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

对于只读迭代,在c++ 98中可以使用std::string::const_iterator,在c++ 11中可以使用For (char const & C:s)或仅For (char C:s)。

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
        }
        //...........
    }

String基本上是一个字符数组,因此您可以指定索引来获取字符。如果您不知道索引,那么您可以像上面的代码一样对其进行循环,但是当您进行比较时,请确保使用单引号(它指定一个字符)。

除此之外,上面的代码是自解释的。