发布日期:2018-03-26
如何使用C++把部分字符串替换为其他字符串?+ 查看更多
如何使用C++把部分字符串替换为其他字符串?
+ 查看更多
发布日期:2018-02-26 14:04
分类:CPlusPlus
浏览次数:110
我想通过c++标准库实现这样:
QString string("hello $name");
string.replace("$name", "Somename");
string.replace("$name", "Somename");
回答
有一个查询字串的方法string(find),并且有另外一个方法用于替换字符串的指定区域string (replace),你可以结合起来使用:
bool replace(std::string& str, const std::string& from, const std::string& to) { size_t start_pos = str.find(from); if(start_pos == std::string::npos) return false; str.replace(start_pos, from.length(), to); return true; } std::string string("hello $name"); replace(string, "$name", "Somename");
从你的评论来看,我认为replaceAll可能是这样的:
void replaceAll(std::string& str, const std::string& from, const std::string& to) { if(from.empty()) return; size_t start_pos = 0; while((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx' } }