如何从C ++中的字符串中删除普通的“\ n”? [重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

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

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

c++ std
2个回答
2
投票

我想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


0
投票
#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
© www.soinside.com 2019 - 2024. All rights reserved.