我有一个字符串,我需要在其中抓取每个字符并进行一些检查。
std::string key = "test"
int i = 0;
while (key.at(i))
{
// do some checking
i++;
}
这样做的问题是,最终索引 i 将超出范围,因此系统将崩溃。我怎样才能解决这个问题?
谢谢!
for(auto i = key.cbegin(); i != key.cend(); ++i)
{
// do some checking
// call *i to get a char
}
std::string key = "test"
for(int i = 0; i < key.length(); i++)
{
//do some checking
}
你可以使用这样的 for 循环。
#include <string>
std::string str("hello");
for(auto &c : str) {
std::cout << c << std::endl;
}
另一种解决方案是使用std::for_each()
并提供一个 lambda 函数来处理每个字符,如下所示:
std::string key = "testing 123";
std::for_each(key.cbegin(), key.cend(), [](char c){ std::cout << c; });
这打印:
testing 123