1

我希望能够遍历 C++ 字符串中的每个字符。最简单的方法是什么?先把它转换成C字符串?我实际上无法让它以任何方式工作,但这是我迄今为止尝试过的:

string word = "Foobar";  
for (int i=0; i<word.length(); ++i) {
  cout << word.data()[i] << endl;
}
4

6 回答 6

5

你应该使用迭代器。此方法适用于大多数 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;                                              
}
于 2013-05-28T15:37:11.050 回答
5

您可以operator[]直接在字符串上使用。它超载了。

string word = "Foobar";  
for (size_t i=0; i<word.length(); ++i) {
  cout << word[i] << endl;
}
于 2013-05-28T15:32:45.787 回答
2

你所拥有的应该工作(对于相当短的字符串);尽管您可以访问每个字符而word[i]无需使用指针。

迂腐地,您应该使用string::size_typeorsize_t而不是int.

您可以使用迭代器:

for (auto it = word.begin(); it = word.end(); ++it) {
    cout << *it << endl;
}

(在 C++11 之前,您必须提供类型名称string::iteratorstring::const_iterator而不是auto)。

在 C++11 中,您可以迭代一个范围:

for (char ch : word) {
    cout << ch << endl;
}

或者您可以使用for_eachlambda:

for_each(word.begin(), word.end(), [](char ch){cout << ch << endl;});
于 2013-05-28T15:36:37.493 回答
2

std::string公开随机访问迭代器,因此您可以使用它们对字符串中的每个字符进行迭代。

于 2013-05-28T15:32:37.713 回答
2

遍历整个字符串的最简单方法是使用基于 C++11 范围的 for 循环:

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;
}
于 2013-05-28T15:33:05.193 回答
0

正如其他人已经指出的那样,最简单的方法是使用在字符串类中重载的 [] 运算符。

string word = "Foobar";  
for (int i=0; i<word.length(); ++i) {
  cout << word[ i ] << endl;
}

如果您已经知道如何遍历 C 字符串,那么有一种机制,类似于 C 中的指针,您可以使用它,而且性能会更高。

字符串字=“Foobar”;
for (string::const_iterator it = word.begin(); it != word.end(); ++it) { cout << *it << endl; }

您有 const 迭代器和常规迭代器。当您计划更改它们指向的数据时,将使用后者进行迭代。前者适用于只读操作,例如控制台转储。

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

希望这可以帮助。

于 2013-05-28T15:40:32.590 回答