如果 s
是 std::string
,那么是否有类似以下的功能?
s.replace("text to replace", "new text");
原文由 neuromancer 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果 s
是 std::string
,那么是否有类似以下的功能?
s.replace("text to replace", "new text");
原文由 neuromancer 发布,翻译遵循 CC BY-SA 4.0 许可协议
有没有像下面这样的功能?
另一种( _除了使用 boost
和不同答案中给出的其他方法_)可能的方法是使用 std::regex_replace
如下所示:
std::string s{"my name is my name and not my name mysometext myto"}; //this is the original line
std::string replaceThis = "my";
std::string replaceWith = "your";
std::regex pattern("\\b" + replaceThis + "\\b");
std::string replacedLine = std::regex_replace(s, pattern, replaceWith);
std::cout<<replacedLine<<std::endl;
原文由 Jason Liam 发布,翻译遵循 CC BY-SA 4.0 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答1.6k 阅读✓ 已解决
替换第一个匹配项
使用
std::string::find
和std::string::replace
的组合。找到第一个匹配项:
替换第一个匹配项:
为您提供方便的简单功能:
用法:
演示。
替换所有匹配项
使用
std::string
作为缓冲区定义此 O(n) 方法:用法:
演示。
促进
或者,使用
boost::algorithm::replace_all
:用法: