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
),以及用另一个字符串替换字符串中特定范围的函数 (replace
),因此您可以将它们组合起来以获得您想要的效果:
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");
<小时>
在回复评论时,我认为 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'
}
}
这篇关于用另一个字符串替换一个字符串的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用另一个字符串替换一个字符串的一部分


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何通过C程序打开命令提示符Cmd 2022-12-09