2012-03-01 70 views
0

我想從文本文件中獲取一些字符串。我知道如何讓一個文本文件的全部串如何使用Qt庫從文本文件中獲取字符串

QTextStream Stream (GEO); 
QString text;  
do  
{  
text = Stream.readLine(); 

} 
while(!text.isNull()); 

這工作正常獲取所有的QString文字下的文字,但我只需要出文本的某​​些特定字符串,示意圖,如:

if the text "start" appears in the Qstring text (or the QTextStream Stream) 

save the following text under QString First 

until the text "end" appears 

有人能告訴我怎麼做,或者甚至給我一個小例子?您可以使用

回答

1

一件事是讓)的「開始」和「結束」用的indexOf(索引和只使用:

QString x = "start some text here end"; 
QString s = "start"; 
QString e = "end" 
int start = x.indexOf(s, 0, Qt::CaseInsensitive); // returns the first encounter of the string 
int end = x.indexOf(e, Qt::CaseInsensitive); // returns 21 

if(start != -1) // we found it 
    QString y = x.mid(start + s.length(), end); 

或midRef如果你不想創建一個新的列表。你可能不得不處理「結束」,否則你可能會從0到-1不會返回任何東西。也許(end> start?end:start)

編輯:沒關係。如果結束== -1,這意味着它將返回所有內容直到結束(默認情況下第二個參數是-1)。如果你不想要這個,你可以用我的例子來代替,並在選擇「結束」時使用某種if語句

編輯:注意到我錯過了文檔,這將def。工作:

#include <QDebug> 

int main(int argc, char *argv[]) { 
    QString x = "start some text here end"; 
    QString s = "start"; 
    QString e = "end"; 
    int start = x.indexOf(s, 0, Qt::CaseInsensitive); 
    int end = x.indexOf(e, Qt::CaseInsensitive); 

    if(start != -1){ // we found it 
     QString y = x.mid(start + s.length(), ((end - (start + s.length())) > -1 ? (end - (start + s.length())) : -1)); // if you dont wanna pass in a number less than -1 
     or 
     QString y = x.mid(start + s.length(), (end - (start + s.length()))); // should not be any issues passing in a number less than -1, still works 

     qDebug() << y << (start + s.length()) << (end - (start + s.length())); 
    } 
} 

這產生了以下resoults。最後兩個數字是「開始」結束和「結束」開始的地方。

X = 「啓動一些文本在這裏結束」=> 「一些這裏文本」 5 16

X = 「一些文本在這裏結束」=>無outprint

X =「測試開始啓動這裏一些文本結束」 =>‘從這裏開始一些文字’13 22

X =‘測試從這裏開始啓動一些文本’=>‘從這裏開始一些文字’13 -14

或者你也可以做它通過使用regEx。這裏寫了一個非常簡單的代碼片段爲您提供:

#include <QDebug> 
#include <QRegExp> 

int main(int argc, char *argv[]) { 
    QRegExp rxlen("(start)(.*(?=$|end))"); 
    rxlen.setMinimal(true); // it's lazy which means that if it finds "end" it stops and not trying to find "$" which is the end of the string 
    int pos = rxlen.indexIn("test start testing some text start here fdsfdsfdsend test "); 

    if (pos > -1) { // if the string matched, which means that "start" will be in it, followed by a string 
     qDebug() << rxlen.cap(2); // " testing some text start here fdsfdsfds" 
    } 
} 

,如果你做到底有「結束」這個作品甚至,那麼它只是解析到該行的末尾。請享用!

+0

thx爲答案。 http://qt-project.org/doc/qt-4.8/qstring.html#mid我只是有一個問題,「結束」,因爲在紀錄片中寫道,第二個參數(在你的例子中n - > 「end」)是從第一個參數「start + s.length()」開始返回的字符數。因此,如果你的第一個參數是起始位置/索引是好的,那麼第二個參數將是等於「結束」的索引/位置的字符串的數量。你能告訴我如何解決這個問題嗎?如果我對第二個參數「end - (start + s.length)」正確的話,應該可以工作,否則真的很好的想法與「s.length()」問候語 – Streight 2012-03-05 23:17:46

+0

。我會在接下來的幾天有空的時候再測試一下,如果有效的話,接受你的回答。 – Streight 2012-03-06 00:08:29

+0

嗨,對不起。閱讀我編輯的版本。還測試了它,併爲您提供輸出 – chikuba 2012-03-06 01:08:04

相關問題