Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove a line from a string with large content in C++?

Tags:

c++

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.

like image 862
BSalunke Avatar asked Nov 23 '11 18:11

BSalunke


Video Answer


2 Answers

One way would be

  1. Use string::find to locate the text newFunction in the string
  2. Use string::find again but starting from where you found newFunction and search for the next '\n'
  3. Use string::rfind starting from the beginning of the string and ending at the position of newFunction for the previous '\n'
  4. Use 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
like image 134
Seth Carnegie Avatar answered Nov 08 '22 18:11

Seth Carnegie


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.

like image 38
jrok Avatar answered Nov 08 '22 20:11

jrok