玖叶教程网

前端编程开发入门

C++ replace函数-C++字符串替换函数

字符串替换,工作中的使用频率也算比较高的,如,将某个字符替换为新的字符、将某个子串替换为新的子串等。

然而在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;
}

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言