用另一个子字符串C ++替换子字符串 [英] Replace substring with another substring C++
本文介绍了用另一个子字符串C ++替换子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将一个字符串中的子字符串替换为C ++中的另一个子字符串,我可以使用什么函数?
How could I replace a substring in a string with another substring in C++, what functions could I use?
eg: string test = "abc def abc def";
test.replace("abc", "hij").replace("def", "klm"); //replace occurrence of abc and def with other substring
推荐答案
在C ++中没有一个内置函数来做到这一点。如果你想用一个子字符串替换另一个子字符串的所有实例,你可以通过调用 string :: find
和 string ::替换
。例如:
There is no one built-in function in C++ to do this. If you'd like to replace all instances of one substring with another, you can do so by intermixing calls to string::find
and string::replace
. For example:
size_t index = 0;
while (true) {
/* Locate the substring to replace. */
index = str.find("abc", index);
if (index == std::string::npos) break;
/* Make the replacement. */
str.replace(index, 3, "def");
/* Advance index forward so the next iteration doesn't pick it up as well. */
index += 3;
}
希望这有助!
这篇关于用另一个子字符串C ++替换子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文