删除大字符串中的空行

Remove empty line in a big 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

这是它在记事本++中的显示方式:

使用正则表达式。关注 link 到 regex reference should get you started. Or yet better regex_replace

您的正则表达式将如下所示

/\n\s*\n/

正则表达式测试可能对在线有帮助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;
}

解决方法:

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++;
  }
}