将字符串的一部分替换为另一个字符串 [英] Replace part of a string with another string
本文介绍了将字符串的一部分替换为另一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有可能在C ++中用另一个字符串替换部分字符串?
Is it possible in C++ to replace part of a string with another string?
基本上,我想这样做:
QString string("hello $name");
string.replace("$name", "Somename");
但我想使用标准C ++库。
But I would like to use the Standard C++ libraries.
推荐答案
有一个函数可以在字符串中找到一个子字符串( find
),以及一个函数,用于将字符串中的特定范围替换为另一个字符串( 替换
),因此您可以组合这些来获得所需的效果:
There's a function to find a substring within a string (find
), and a function to replace a particular range in a string with another string (replace
), so you can combine those to get the effect you want:
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");
c $ c> 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'
}
}
这篇关于将字符串的一部分替换为另一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文