字符串替换,工作中的使用频率也算比较高的,如,将某个字符替换为新的字符、将某个子串替换为新的子串等。
然而在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;
}