2017-06-19 143 views
0

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

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

你永远不会初始化'OldCaractere','NumberReturnCaractere','NumberDoubleReturnCaractere'所以它们包含垃圾。 – VTT

+0

为什么不使用strstr来查找\ n \ n或类似的东西? – ArBel

+0

正如你有这个要求,你可以改变你的设计是一个'std :: vector >或'std :: list >'外容器中的每个元素是原始文本的一行? –

回答

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

这段代码有几个bug:1)有符号和无符号数据类型的比较。 2)不仅删除空行,而且删除空行之后的所有空行字符。 3)如果你期望有很多空行的长字符串,那么你会有很多'erase()'调用来移动字符串,因此你的性能会受到影响。 –

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

您好,感谢您的回复,我不明白如何在我的情况下使用它,你能给我一个工作代码吗? – Anonyme

+0

在我编辑的帖子中查看示例。我也改变了引用regex_replace而不是我原来使用的regex_search。 –