C++字符串点滴以及java字符串replace方法回顾

C++字符串点滴以及java字符串replace方法回顾 - sharpstill - 博客园

C++字符串点滴以及java字符串replace方法回顾

 

类似java或python的string的replace方法?
string replace( pos ,len , new_str );
C++的string的replace的原始定义的第一个参数起始替换下标,第二个参数是从起始替换下标开始替换的len个字符,第三个参数是new_str.
与python的字符串替换略有不同,现在比如我要把str = "Hello world  mac"中的mac替换成jobs
1. 替换第一次出现的字符串mac(只替换第一次出现的字符串,不是replaceAll)
string old_word= "mac";
string hello ="hello world "+old_word;
hello.replace(hello.find(old_word),old_word.size(),"jobs");
2 .替换所有出现的字符串mac,和replaceAll一样:(暂未解决,不行就while循环办法1,直到替换为止)
标准库中的string未提供此replaceAll方法。
有两个办法:
1.Boost内置方法(未找到,学到Boost再说)
2.C语言的办法(摘抄代码):
#include <stdio.h>
#include <string.h>

char *replace_str(char *str, char *orig, char *rep)
{
  static char buffer[4096];
  char *p;
  if(!(p = strstr(str, orig)))  // Is 'orig' even in 'str'?
    return str;
  strncpy(buffer, str, p-str); // Copy characters from 'str' start to 'orig' st$
  buffer[p-str] = '';
  sprintf(buffer+(p-str), "%s%s", rep, p+strlen(orig));
  return buffer;
}
int main(void)
{
  puts(replace_str("Hello, world!", "world", "Miami"));
  return 0;
}

原文地址:https://www.cnblogs.com/lexus/p/3483842.html