我希望能够遍历C++字符串中的每个字符。最简单的方法是什么?先将它转换为C字符串?我还没有真正能够得到它的工作的任何方式,但这里是我试过到目前为止:索引C++字符串的最简单方法是什么?
string word = "Foobar";
for (int i=0; i<word.length(); ++i) {
cout << word.data()[i] << endl;
}
我希望能够遍历C++字符串中的每个字符。最简单的方法是什么?先将它转换为C字符串?我还没有真正能够得到它的工作的任何方式,但这里是我试过到目前为止:索引C++字符串的最简单方法是什么?
string word = "Foobar";
for (int i=0; i<word.length(); ++i) {
cout << word.data()[i] << endl;
}
您可以直接在字符串上使用operator[]
。它超载。
string word = "Foobar";
for (size_t i=0; i<word.length(); ++i) {
cout << word[i] << endl;
}
std::string
公开随机访问迭代器,所以你可以用这些来的每一个字符迭代器在字符串中。
整个字符串迭代最简单的方法是使用基于for循环一个C++ 11范围:
for (auto c : word)
{
std::cout << c << std::endl;
}
否则,可以通过operator[]
访问单个元件,你会阵列,或使用迭代器:
for (std::string::size_type i = 0, size = word.size(); i < size; ++i)
{
std::cout << word[i] << std::endl;
}
for (auto i = word.cbegin(), end = word.cend(); i != end; ++i)
{
std::cout << *i << std::endl;
}
提醒:这种表示法是C++ 11语法,不适用于C++ x03 –
在第二个循环中,auto必须为'i'和'size'推导出相同的类型。但'i'是用unsigned int和'size'与std :: string :: size_type(几乎可以肯定是一个'std :: size_t')初始化的。这些可能是不同的类型(例如,在64位Windows上是LLP64而不是LP64),从而导致编译器错误。 –
@AdrianMcCarthy好点。它在我测试过的一个平台上工作。我会解决这个问题。 – juanchopanza
你应该有什么工作(对于合理的短字符串);虽然你可以访问每个字符作为word[i]
而不用弄乱指针。
迂回地,你应该使用string::size_type
或size_t
而不是int
。
你可以使用一个迭代器:
for (auto it = word.begin(); it = word.end(); ++it) {
cout << *it << endl;
}
(早于C++ 11,你必须给类型名称string::iterator
或string::const_iterator
而非auto
)。
在C++ 11,你可以遍历一个范围:
for (char ch : word) {
cout << ch << endl;
}
,或者您可以使用for_each
与拉姆达:
for_each(word.begin(), word.end(), [](char ch){cout << ch << endl;});
您应该使用迭代器。此方法适用于大多数STL的容器。
#include <iostream>
#include <string>
int main()
{
std::string str("Hello world !");
for (std::string::iterator it = str.begin(); it != str.end(); ++it)
std::cout << *it << std::endl;
}
最简单的方式做到这一点,因为其他人已经指出的那样,是使用[]操作,在String类重载。
string word = "Foobar";
for (int i=0; i<word.length(); ++i) {
cout << word[ i ] << endl;
}
如果你已经知道如何遍历C字符串,然后有一个机制,类似于C的指针,你可以使用,这将是很多更好的性能。
string word =“Foobar”;
为(字符串::为const_iterator它= word.begin();!它= word.end(); ++它) { COUT < < *它< < ENDL; }
你有常量迭代器和常规迭代器。当你计划改变它们指向的数据将迭代时,将使用后者。前者适用于只读操作,如控制台转储。
string word = "Foobar";
for (string::iterator it = word.begin(); it != word.end(); ++it)
{
(*it)++;
}
通过上面的代码,您将使用下一个字符“加密”您的单词。
最后,你总是想回到C指针的可能性:
string word = "Foobar";
const char * ptr = word.c_str();
for (; *ptr != 0; ++ptr)
{
(*ptr)++;
}
希望这有助于。
'operator []'被重载为'std :: string'。所以简单地说'cout << word [i] << endl;'。 –