0

I would like to find 3 or more occurrences of a within a std::string in order to replace.

For example:

std::string foo = "This is a\n\n\n test";
std::string bar = "This is a\n\n\n\n test";
std::string baz = "This is a\n\n\n\n\n test";
std::string boo = "This is a\n\n\n\n\n\n test";
// ... etc.

Should all be converted to:

std::string expectedResult = "This is a\n\n test";

Vanilla stl would be appreciated (no regexp libs or boost) if possible.

4

3 に答える 3

2

これにより、連続した \n が検出され、それらが置き換えられます。

size_type i = foo.find("\n\n\n");
if (i != string::npos) {
    size_type j = foo.find_first_not_of('\n', i);
    foo.replace(i, j - i, "\n\n");
}
于 2012-10-18T20:51:33.113 に答える
0

変更したい各文字列を処理する関数を記述します。

各文字列を一度に1文字ずつ読み取ります。aとbの2つのchar変数を追跡します。読んだ文字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
    }
}

STLの何かを直接使用して、求めていることを達成できるかどうかは100%わかりませんが、ご覧のとおり、このロジックは実装するコードがそれほど多くありません。

于 2012-10-18T20:51:12.960 に答える
0

検索と置換を使用できます。(これは "\n\n\n..." -> "\n\n" を置き換えます)。string::find に位置を渡して、文字列の先頭を再度検索する必要がないようにすることができます (最適化)。

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

そして、これは "\n\n\n\n.." -> "\n" を置き換えます

  int pos = 0;
  while ((pos = s.find ("\n\n", pos)) != s.npos)
    s.replace (pos, 2, "\n", 1);
于 2012-10-18T20:55:52.197 に答える