替换字符串中的3个或更多字符出现

Replace 3 or more occurrences of character within string

本文关键字:字符 字符串 3个 替换      更新时间:2023-10-16

我想在std :: string中找到3个或多个出现以替换。

例如:

std::string foo = "This is annn test";
std::string bar = "This is annnn test";
std::string baz = "This is annnnn test";
std::string boo = "This is annnnnn test";
// ... etc.

应该将所有全部转换为:

std::string expectedResult = "This is ann test";

香草stl将不胜感激(如果可能

这应该找到连续 n并替换它们:

size_type i = foo.find("nnn");
if (i != string::npos) {
    size_type j = foo.find_first_not_of('n', i);
    foo.replace(i, j - i, "nn");
}

编写一个函数来处理您对修改感兴趣的每个字符串:

一个时间读取每个字符串一个字符。跟踪2个字符变量:a和b。对于您阅读的每个字符c,请执行:

if ( a != b ) {
    a = b;
    b = c;
} else if ( a == b ) {
    if ( a == c ) {
        // Put code here to remove c from your string at this index
    }
}

我不是100%确定您是否可以直接使用STL来完成您的要求,但是您可以看到此逻辑并不是要实现的代码太多。

您可以使用查找和替换。(这将替换" n n n ..." ->" n n")。您可以将位置传递给字符串::查找,以便您不必再次搜索字符串的开始(优化)

  int pos = 0;
  while ((pos = s.find ("nnn", pos)) != s.npos)
    s.replace (pos, 3, "nn", 2);

这将替换" n n n n n .." ->" n"

  int pos = 0;
  while ((pos = s.find ("nn", pos)) != s.npos)
    s.replace (pos, 2, "n", 1);