如何解决用\ n替换\\ n的最有效方法是什么
我问这个是因为我正在使用SFML字符串。 sf :: String在\ n存在时不会插入新行。
如果不使用3/4 STL算法,我似乎找不到办法。
std::replace_if(str.begin(),str.end(),[](const char&c](return c == '\\n'),'\n'
});
不起作用。字符串保持不变。
我还尝试用临时\\
代替~
出现。这可行,但是当我用~
替换\
时,它添加了\\
而不是\
我提出了一种解决方案,方法是在\n
插入之后手动替换并删除重复项:
for (auto it = str.begin(); it != str.end(); ++it) {
if (*it == '\\') {
if (it + 1 != str.end()) {
if (*(it + 1) != 'n') continue;
*it = '\n';
str.erase(it + 1);
}
}
}
解决方法
您可以这样做:
str = std::regex_replace(str,std::regex(R"(\\n)"),"\n")
,
问题在于'\\n'
不是单个字符而是两个字符。因此,它需要存储在字符串"\\n"
中。但是现在std::replace_if
不起作用,因为它对元素起作用并且std::string
的元素是单个字符。
您可以编写一个新函数来替换字符串中的子字符串,然后调用它。例如:
std::string& replace_all(std::string& s,std::string const& from,std::string const& to)
{
if(!from.empty())
for(std::string::size_type pos = 0; (pos = s.find(from,pos) + 1); pos += to.size())
s.replace(--pos,from.size(),to);
return s;
}
// ...
std::string s = "a\\nb\\nc";
std::cout << s << '\n';
replace_all(s,"\\n","\n");
std::cout << s << '\n';
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。