用一些字符串替换字符串中的char

Mad*_*adu 3 c++ string algorithm


我想用字符串替换字符串中的字符.我可以就地做吗?由于新字符串的长度大于原始字符串.问题是我可以使用额外的缓冲区吗?例如

void replaceChar(std::string &input, std::string replacementString, char charToReplace)
{
//some code here. No additional buffer
}

void main(){

  std::string input = "I am posting a comment on LinkedIn";
  std::string replacementString = "pppp";
  char charToReplace = 'o';
  replaceChar(input, replacementString, charToReplace);
}
Run Code Online (Sandbox Code Playgroud)

我只想要策略(算法).如果算法的设计保持一定的语言,一旦它被启动就不会动态增加或减少字符串长度,这将是很好的

Jer*_*fin 5

std::string有一个replace成员,但它的工作方式是数字位置,而不是字符串的先前内容.因此,您通常必须将它与find循环中的成员组合,如下所示:

std::string old("o");

int pos;

while ((pos = x.find(old)) != std::string::npos)
    x.replace(pos, old.length(), "pppp");
Run Code Online (Sandbox Code Playgroud)

就个人而言,我很少关注字符串调整大小的频率,但如果它是一个主要问题,你可以std::count用来查找old字符串出现次数,乘以旧字符串和新字符串之间的大小差异,以及使用std::string::reserve()预留足够的空间.但请注意,reserve在C++ 11中添加了 - 较旧的实现将不具备它.

编辑:虽然它不是你所使用的字符串的问题,正如@ipc所指出的,如果替换字符串包含要替换的值的实例,这将无法正常工作.如果您需要处理它,您需要在字符串中提供开始每次搜索的偏移量:

int pos = 0;

while ((pos = x.find(old, pos)) != std::string::npos) {
    x.replace(pos, old.length(), rep);
    pos += rep.length();
}
Run Code Online (Sandbox Code Playgroud)

或者,for在这种情况下,您可能更喜欢循环:

    std::string old("o");
    std::string rep("pop");

for (int pos=0; 
    (pos = x.find(old, pos)) != std::string::npos; 
    pos+=rep.length())
{
    x.replace(pos, old.length(), rep);
}
Run Code Online (Sandbox Code Playgroud)