【问题标题】:Remove empty line in a big string删除大字符串中的空行
【发布时间】:2017-06-19 09:37:09
【问题描述】:

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

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

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

【问题讨论】:

  • 你永远不会初始化OldCaractereNumberReturnCaractereNumberDoubleReturnCaractere,所以它们包含垃圾。
  • 为什么不使用 strstr 来查找 \n\n 或类似的东西?
  • 既然您有这个要求,您能否将您的设计更改为std::vector<std::string>>std::list<std::string>>,其中外部容器中的每个元素都是原始文本的一行?
  • 我无法更改设计。

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


【解决方案1】:

使用正则表达式。以下指向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;
}

【讨论】:

  • 您好,感谢您的回复,我不明白在我的情况下如何使用它,您能给我一个工作代码吗?
  • 查看我编辑的帖子中的示例。我还更改了对 regex_replace 的引用,而不是我最初使用的 regex_search。
【解决方案2】:

解决办法:

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

【讨论】:

  • 这段代码有几个错误:1)比较有符号和无符号数据类型。 2)它不仅删除空行,还删除空行之后的行开头的所有空白字符。 3) 如果您期望有很多空行的长字符串,那么您将有很多 erase() 调用移动字符串,因此您的性能会受到影响。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-02
  • 1970-01-01
  • 2013-05-10
  • 1970-01-01
  • 2019-06-14
  • 2011-03-24
相关资源
最近更新 更多