【问题标题】:Knowing the end of a std::string in a loop知道循环中 std::string 的结尾
【发布时间】:2014-04-03 00:22:38
【问题描述】:

我想知道如何知道循环中 std::string 的结尾?

例如:

while(string.eof()) {}

记住它与 std::string 一起使用

谢谢大家。

【问题讨论】:

  • 使用str.begin()str.end()
  • 请注意,while (!eof()) 通常使用非常错误。

标签: c++ string c++11 std


【解决方案1】:

您可以像循环标准库容器一样循环字符串:

for (auto c : s)
{
  // do something with c
}

for (auto it = s.begin(), end = s.end(); it != end; ++it)
{
  // do something with it
}

s 是字符串。

【讨论】:

  • @SH.0x90 好的,不要在循环中使用cit
  • 你可以为像我这样认为迭代器破坏性能的偏执狂的人添加整数:D;注意:将 iter.end() 拉入变量,编译器应该这样做,但你永远不知道
  • @TheOne 好的,我做到了。如果您在非常量容器上进行迭代并且编译器无法判断您是否在循环内修改它,这很重要。
  • @Creris:上一次我在几年前使用 GNU C++ 库测量它时,迭代器的性能优于使用 std::string 的数组索引。
【解决方案2】:

你可以使用迭代器

string str="abcd";
string::iterator it=str.rbegin();//iterator pointing on d

如果你想在最后一个字符之前做一些事情,你可以这样做

for (string::iterator it2=str.begin(); it"!=str.rbegin();++it){
   cout<<"Inside the string but not the last character\n";
}

【讨论】:

  • 你到底是什么意思?
  • 例如:当一个字符串的结尾,一个字符串的最后一个字符没有来,我会在循环内部做一些事情,一直持续到字符串的结尾来,当它来了,我打破了循环。 - 看 eof 的例子。
【解决方案3】:

"我不想和字符串交互,只想要一个循环,而 字符串的结尾没有出现。”

实际上,字符串是一个容器(特定数组),而不是文件。它不支持任何state,也没有像eof 这样的方法。所以你不能这样做。

如果您有通常的数组char buf[SZ];,那么“数组的末尾没有到来”是什么? 毫无意义。数组索引可以指向最后一个元素,上面显示的字符串迭代器也是如此。

【讨论】:

  • 是的,我明白了。看到上面的答案,我意识到我需要使用迭代器来操作和“知道”字符串的结尾。谢谢。
猜你喜欢
  • 2016-02-03
  • 1970-01-01
  • 2012-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-02
  • 2015-07-18
  • 2014-09-18
相关资源
最近更新 更多