-1

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

Anonymous
  • 468
  • 5
  • 26

2 Answers2

3

Use regular expression. Following link to regex reference should get you started. Or yet better regex_replace.

Your regular expression will look like this

/\n\s*\n/

For regular expression tests might be helpful online regex tester.

#include <iostream>
#include <string>
#include <regex>

int main ()
{
  std::string s ("there is a line \n    \nanother line\n   \nand last one in the string\n");
  std::regex e ("\\n\\s*\\n");
  std::cout << std::regex_replace (s,e,"\n");
  return 0;
}
Marek Vitek
  • 1,573
  • 9
  • 20
  • Hello, thanks for your response, I don't understand how to use it in my case, can you give me a working code ? – Anonymous Jun 19 '17 at 10:09
  • See example in my edited post. I have also changed reference to regex_replace instead of regex_search I used originally. – Marek Vitek Jun 19 '17 at 11:26
0

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++;
  }
}
Anonymous
  • 468
  • 5
  • 26
  • 1
    This code has several bugs in it: 1) comparison of signed and unsigned data types. 2) it removes not only empty lines, but also all whitespace characters from the beginning of the line following the empty one. 3) if you expect long strings with lot of empty lines, then you will have lot of `erase()` calls that move the string and thus your performance will suffer. – Marek Vitek Jun 23 '17 at 12:16