【问题标题】:How to delete plain "\n" from a string in C++? [duplicate]如何从 C++ 中的字符串中删除纯“\n”? [复制]
【发布时间】:2018-09-11 09:48:40
【问题描述】:

如上所述,我试图从一行中删除两个字符子字符串(不是换行符,只是纯文本)。

我现在正在做的是line.replace(line.find("\\n"), 3, "");,因为我想逃避它,但我收到调试错误,说 abort() 已被调用。此外,我不确定大小为 3,因为不应将第一个斜杠视为文字字符。

【问题讨论】:

  • 请创建一个minimal reproducible example。我敢肯定你在第 23 行有错字,但你还是最好把代码给我们看看
  • 您想删除两个字符('\' 和 'n'),而不是三个。您还需要检查是否找到了该字符串。
  • @Swift-FridayPie 为什么有人会使用正则表达式删除常量?
  • @Swift-FridayPie 现在你遇到了\\n 问题。

标签: c++ std


【解决方案1】:

我猜this 正是您要找的:

std::string str = "This is \\n a string \\n containing \\n a lot of \\n stuff.";
const std::string to_erase = "\\n";

// Search for the substring in string
std::size_t pos = str.find(to_erase);
while (pos != std::string::npos) {
    // If found then erase it from string
    str.erase(pos, to_erase.length());
    pos = str.find(to_erase);
}

请注意,您可能会得到 std::abort,因为您将 std::string::npos 或长度 3(不是 2)传递给 std::string::replace

【讨论】:

  • 你当然是对的,我打字很匆忙。代码现在按预期运行,您可以在这里看到它的实际效果:ideone.com/nHRc0k
  • 这正是我想要的,非常感谢!
【解决方案2】:
#include <iostream>
#include <string>
int main()
{

std::string head = "Hi //nEveryone. //nLets //nsee //nif //nthis //nworks";
std::string sub = "//n";
std::string::iterator itr;
for (itr = head.begin (); itr != head.end (); itr++)
{
  std::size_t found = head.find (sub);
  if (found != std::string::npos)
head.replace (found, sub.length (), "");

}
 std::cout << "after everything = " << head << std::endl;
}

我得到的输出是:

after everything = Hi Everyone. Lets see if this works

【讨论】:

  • 一切都很好,但为什么 / 而不是 \ ?这就是这个问题的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-04
  • 2014-02-15
  • 2011-04-17
  • 2011-05-10
  • 1970-01-01
  • 2014-01-26
  • 2019-06-01
相关资源
最近更新 更多