0

我有一个字符串,我需要在其中抓取每个字符并进行一些检查。

std::string key = "test"
int i = 0;
while (key.at(i))
{
    // do some checking
    i++;
}

这样做的问题是,最终索引 i 将超出范围,因此系统将崩溃。我怎样才能解决这个问题?

谢谢!

4

4 回答 4

1
for(auto i = key.cbegin(); i != key.cend(); ++i)
{
    // do some checking
    // call *i to get a char
}
于 2012-07-03T01:42:05.863 回答
1
std::string key = "test"
for(int i = 0; i < key.length(); i++)
{
    //do some checking
}
于 2012-07-03T01:36:41.303 回答
1

你可以使用这样的 for 循环。

#include <string>

std::string str("hello");

        for(auto &c : str) {
            std::cout << c << std::endl;
        }
于 2018-08-14T08:10:37.120 回答
0

另一种解决方案是使用std::for_each()并提供一个 lambda 函数来处理每个字符,如下所示:

std::string key = "testing 123";
std::for_each(key.cbegin(), key.cend(), [](char c){ std::cout << c; });

这打印:

testing 123
于 2018-08-16T03:59:03.180 回答