c++ - 在 for 循环中使用 erase() 只删除第一行

标签 c++ string for-loop line erase

我正在尝试在 for 循环中使用 std::string::erase() 从字符串中一次删除一行,但它只会删除第一行。

为什么只删除第一行?

Using namespace std;
String = "Adam\nBen\nCallum\nDennis\n"
for(i=0; i<3; i++){
  size_t endofstring = string.find("\n");
  string.erase(0,endofstring);
}

最佳答案

发生这种情况是因为 erase() 的第二个参数是一个长度,当您传递索引时,它会删除所有内容,但不包括 \n.

按照您的预期,您似乎也想删除 \n,所以使用 index+1:

string.erase(0, endofstring+1)

有关更多引用,请参阅 http://www.cplusplus.com/reference/string/string/erase/

关于c++ - 在 for 循环中使用 erase() 只删除第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50089237/

相关文章:

c++ - 这是什么意思?

c++ - WinAPI 函数 Hook 以捕获网络

c++ - 忽略空白字符

c - For 循环遍历数组导致无限循环

arrays - 在 plpgsql 中循环遍历数组维度

c++ - 在抽象类 c 的子类中使用来自抽象类的引用

Python:在循环中连接字符串和整数

php - 从 PHP 数组中提取字符串

string - 如何在 Rust 中将字符串转换为向量?

python - Python 中的字符串索引超出范围