对于字符串中的每个字符 [英] For every character in string

查看:124
本文介绍了对于字符串中的每个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何对C ++中的字符串中的每个字符执行一个for循环?
我知道这是可能在python,但我不知道是否可能在C + +

How would I do a for loop on every character in string in C++? I know it's possible in python, but I don't know if it's possible in C++

推荐答案


  1. 使用基于范围的for循环(它来自C ++ 11,最近已经支持)通过 std :: string 的字符循环释放GCC,clang和VC11测试版):

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


  • 循环使用 std :: string 与迭代器:

    std::string str = ???;
    for(std::string::iterator it = str.begin(); it != str.end(); ++it) {
        do_things_with(*it);
    }
    


  • 循环使用 std :: string 与一个老式的for循环:

  • Looping through the characters of a std::string with an old-fashioned for-loop:

    for(std::string::size_type i = 0; i < str.size(); ++i) {
        do_things_with(str[i]);
    }
    


  • 循环通过以空字符结尾的字符数组的字符: / p>

  • Looping through the characters of a null-terminated character array:

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


  • 这篇关于对于字符串中的每个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆