我有一个包含以下内容的字符串:
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
一种方法是
string::find查找文本newFunctionstring::find再次使用,但从您找到的位置开始,newFunction然后搜索下一个'\n'string::rfind从字符串的开头开始,newFunction到前一个的位置结束'\n'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)