用\ 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")

Demo

,

问题在于'\\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';

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...