Search code examples
c++charnewlinecarriage-returnblank-line

Remove empty line in a big string


I would like to remove an empty line in a big string (not a file). This is the string :

The unique begin of a line in my string, after that a content same endline


        The unique begin of a line in my string, after that a content same endline
        The unique begin of a line in my string, after that a content same endline

This is how it appears on notepad++:

Notepad


Solution

  • The solution :

    string myString = "The string which contains double \r\n \r\n so it will be removed with this algorithm.";
    int myIndex = 0;
    while (myIndex < myString.length()) {
      if (myString[myIndex] == '\n') {
        myIndex++;
        while (myIndex < myString.length() && (myString[myIndex] == ' ' || myString[myIndex] == '\t' || myString[myIndex] == '\r' || myString[myIndex] == '\n')) {
          myString.erase(myIndex, 1);
        }
      } else {
        myIndex++;
      }
    }