网站首页 > 基础教程 正文
字符串替换,工作中的使用频率也算比较高的,如,将某个字符替换为新的字符、将某个子串替换为新的子串等。
然而在C/C++的世界里这些都不是现成的东西,所以这里把我自己项目中用到的提取出来分享给大家。
【虽然可以收藏备用,但是作为C/C++程序员,原理不但要会、自己手写也会才是合格的C/C++程序员哦】
代码示例如下(直接拿去用):
#include <string>
#include <iostream>
using namespace std;
/**
* @brief 字符串替换,全部替换
*
* @param str 源字符串
* @param from 待替换的字符串
* @param to 替换的内容
* @param count 替换的次数-1表示替换所有, 其它为替换的次数
* @return string
*/
string replace(string str, const string &from, const string &to, int count = -1) {
if (count == 0) {
return str;
}
int curCount = 0;
size_t pos = 0;
while ((pos = str.find(from, pos)) != std::string::npos) {
if (count != -1 && curCount >= count) {
break;
}
str.replace(pos, from.length(), to);
pos += to.length();
curCount++;
}
return str;
}
// 测试
int main() {
// 输入"hello" 输出 "yello"
cout << replace("hello", "h", "y") << endl;
// 输入"hello" 输出 "hey"
cout << replace("hello", "llo", "y") << endl;
// 输入"hello hello hello 输出 "he hello hello"
cout << replace("hello hello hello", "llo", "", 1) << endl;
return 0;
}
猜你喜欢
- 2024-11-11 C++经典算法问题:背包问题(迭代+递归算法)!含源码示例
- 2024-11-11 C++进阶教程:C#嵌套循环 c++嵌套循环break
- 2024-11-11 C++经典算法 穷举法 穷举算法的优点
- 2024-11-11 C++数据结构-- 递归 排序 c++使用递归函数实现全排列
- 2024-11-11 如何使用c++发送window消息通知 c++怎么发给别人
- 2024-11-11 C++学习:循环练习题(一) c++循环结构例题解析
- 2024-11-11 C/C++最细循环解析 c++循环结构23道题
- 2024-11-11 网络编程——C++实现socket通信(TCP)
- 2024-11-11 C++ GESP 2023年6月真题 c++历年真题解析
- 2024-11-11 「C语言重点难点精讲」关键字精讲1
- 最近发表
- 标签列表
-
- gitpush (61)
- pythonif (68)
- location.href (57)
- tail-f (57)
- pythonifelse (59)
- deletesql (62)
- c++模板 (62)
- css3动画 (57)
- c#event (59)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- exec命令 (59)
- canvasfilltext (58)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- node教程 (59)
- console.table (62)
- c++time_t (58)
- phpcookie (58)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)