删除大字符串中的空行

时间:2017-06-19 09:37:10

标签: c++ char newline carriage-return blank-line

我想删除大字符串(不是文件)中的空行。 这是字符串:

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

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

Notepad

2 个答案:

答案 0 :(得分:3)

使用正则表达式。点击regex reference链接可以帮助您入门。或者更好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;
}

答案 1 :(得分: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++;
  }
}