2017-06-19 63 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。 –