c++ - 对于字符串中的每个字符

标签 c++ loops for-loop character

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

最佳答案

  1. 循环通过 characters std::string,使用基于范围的 for 循环(它来自 C++11,已在 GCC、clang 和 VC11 beta 的最新版本中得到支持):

    std::string str = ???;
    for(char& c : str) {
        do_things_with(c);
    }
    
  2. 使用迭代器循环遍历 std::string 的字符:

    std::string str = ???;
    for(std::string::iterator it = str.begin(); it != str.end(); ++it) {
        do_things_with(*it);
    }
    
  3. 使用老式 for 循环遍历 std::string 的字符:

    std::string str = ???;
    for(std::string::size_type i = 0; i < str.size(); ++i) {
        do_things_with(str[i]);
    }
    
  4. 循环遍历以空字符结尾的字符数组的字符:

    char* str = ???;
    for(char* it = str; *it; ++it) {
        do_things_with(*it);
    }
    

关于c++ - 对于字符串中的每个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9438209/

相关文章:

ios - Swift 3 构建数组(不知道如何描述)

java - 如何更改使用外循环和内循环创建的网格上的下一列?

bash - bash for 循环中的后台进程

c++ - 在类中声明类型别名的替代方法

c++ - 如何将字符串迭代器指向的数据推回到字符串 vector 中

javascript - 如何在循环内将 Object.entry 中的值与另一个键值相乘?

bash - 在文件名中使用计数变量

python - 双 For 循环迭代。两个列表比较

c++ - 使 Xerces 解析字符串而不是文件

c++ - Visual Studio 在 C++ 项目中自动为什么生成数据库文件?