如何从C++中具有大内容的字符串中删除一行?

BSa*_*nke 4 c++

我有一个包含以下内容的字符串:

string myString;
cout<<"String  :"<<endl<<myString<<endl;
Run Code Online (Sandbox Code Playgroud)

输出是:

String :
/this/is/first/line/library.so
cv_take_Case::newFuncton(int const&)
cv_take_Case::anotherMethod(char const&)
thi_is::myMethod
.
.
.
sdfh dshf j dsjfh sdjfh 
Run Code Online (Sandbox Code Playgroud)

所以在上面的例子中,如何删除包含"newFuncton"字符串的整行.

Set*_*gie 11

一种方法是

  1. 用于在字符串中string::find查找文本newFunction
  2. string::find再次使用,但从您找到的位置开始,newFunction然后搜索下一个'\n'
  3. 使用string::rfind从字符串的开头开始,newFunction到前一个的位置结束'\n'
  4. 使用string::erase卸下两个新行之间的文本,只留下一个换行符.

例:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string text = "hello\nblahafei fao ef\nthis is a string\nhello newFunction stuff\nasdfefe\nnopef";

    size_t nFPos = text.find("newFunction");
    size_t secondNL = text.find('\n', nFPos);
    size_t firstNL = text.rfind('\n', nFPos);

    cout << "Original string: " << '\n' << text << '\n' << endl;

    text.erase(firstNL, secondNL - firstNL);

    cout << "Modified string: " << '\n' << text << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Original string: 
hello
blahafei fao ef
this is a string
hello newFunction stuff
asdfefe
nopef

Modified string: 
hello
blahafei fao ef
this is a string
asdfefe
nopef
Run Code Online (Sandbox Code Playgroud)