首页 > 解决方案 > 如何从 C++ 中的字符串中删除纯“\n”?

问题描述

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

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

标签: c++std

解决方案


我想正是您正在寻找的:

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.


推荐阅读