在C++中是否可以用另一个字符串替换字符串的一部分?
基本上,我想这样做:
QString string("hello $name");
string.replace("$name", "Somename");
Run Code Online (Sandbox Code Playgroud)
但我想使用标准C++库.
有没有办法用另一个字符串替换所有出现的子字符串std::string?
例如:
void SomeFunction(std::string& str)
{
str = str.replace("hello", "world"); //< I'm looking for something nice like this
}
Run Code Online (Sandbox Code Playgroud) 我一直在寻找一种在 std::string 中转义单引号的解决方案,但没有找到一种干净的方法来做到这一点。
这篇文章给出了几个这样的解决方案:
std::wstring regex_escape(const std::wstring& string_to_escape) {
static const boost::wregex re_boostRegexEscape( _T("[\\^\\.\\$\\|\\(\\)\\[\\]\\*\\+\\?\\/\\\\]") );
const std::wstring rep( _T("\\\\\\1&") );
std::wstring result = regex_replace(string_to_escape, re_boostRegexEscape, rep, boost::match_default | boost::format_sed);
return result;
}
Run Code Online (Sandbox Code Playgroud)
很酷但对我的要求来说太复杂了。有没有更简单、更容易理解(和标准)的方法来解决这个问题(不影响性能)?
注意:也许我发现上面的内容太复杂了,因为我真的不明白这条线在做什么: const std::wstring rep( _T("\\\\\\1&") )
我有一个字符串AB C.我需要在C++中用下划线(_)替换空格.是否有像perl或java一样的函数?
输入:
char* string = "A B C"
Run Code Online (Sandbox Code Playgroud)
产量
A_B_C
Run Code Online (Sandbox Code Playgroud)