2014-09-25 93 views
0

我試圖替換特定行的文本,但沒有成功。 (我搜索了很多,但我不一無所獲)從特定行中替換文本

類似:

hello 
my 
friend! 

更換2號線到一些文字:

hello 
AEEEHO NEW LINE TEXT 
friend! 

我創建了一個QStringList中,並試圖逐行讀取文本並通過更改行來添加到此列表中,但沒有成功。

 int line = 1; // to change the second line 
     QString newline = "my new text"; 
     QStringList temp; 

     int i = 0; 
     foreach(QString curlineSTR, internalCode.split('\n')) 
     { 
      if(line == i) 
       temp << newline; 
      else 
       temp << curlineSTR; 
      i++; 
     } 

     internalCode = ""; 
     foreach(QString txt, temp) 
      internalCode.append(QString("%1\n").arg(txt)); 

回答

2

我相信你正在尋找QRegExp處理換行符,做這樣的事情:

QString internalcode = "hello\nmy\nfriend!"; 

int line = 1; // to change the second line 
QString newline = "another text"; 

// Split by newline command 
QStringList temp = internalcode.split(QRegExp("\n|\r\n|\r")); 
internalcode.clear(); 

for (int i = 0; i < temp.size(); i++) 
{ 
    if (line == i) 
     internalcode.append(QString("%0\n").arg(newline)); 
    else 
     internalcode.append(QString("%0\n").arg(temp.at(i))); 
} 

//Use this to remove the last newline command 
internalcode = internalcode.trimmed(); 

qDebug() << internalcode; 

和輸出:

"hello 
another text 
friend!" 
+0

謝謝!工作正常。 – Niunzin 2014-09-25 20:03:10