如何查找和替换字符串? [英] How to find and replace string?
本文介绍了如何查找和替换字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果 s
是 std :: string
,那么是否有类似下面的函数?
If s
is a std::string
, then is there a function like the following?
s.replace("text to replace", "new text");
推荐答案
尝试 std :: string :: find
和 std :: string :: replace
。
这获得位置:
size_t f = s.find("text to replace");
这取代了文本:
s.replace(f, std::string("text to replace").length(), "new text");
现在,您可以简单地创建一个函数:
Now you can simply create a function for your convenience:
std::string myreplace(std::string &s,
const std::string &toReplace,
const std::string &replaceWith)
{
return(s.replace(s.find(toReplace), toReplace.length(), replaceWith));
}
这篇关于如何查找和替换字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文