i have a string with following content:
string myString;
cout<<"String :"<<endl<<myString<<endl;
Output is :
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
so in above example, how to remove the entire line containing "newFuncton" string.
One way would be
string::find
to locate the text newFunction
in the stringstring::find
again but starting from where you found newFunction
and search for the next '\n'
string::rfind
starting from the beginning of the string and ending at the position of newFunction
for the previous '\n'
string::erase
to remove the text between the two newlines, leaving only one newline.Example:
#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;
}
Outputs:
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
You might want to organize it in a function, for example:
void RemoveLine(std::string& source, const std::string& to_remove)
{
size_t m = source.find(to_remove);
size_t n = source.find_first_of("\n", m + to_remove.length());
source.erase(m, n - m + 1);
}
Usage:
RemoveLine(myString, std::string("cv_take_Case::newFunction"));
Note that I assumed the part we search for will be at the beggining of the line. For a more robust solution look at Seth Carnegie's answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With