2012-03-07 71 views
1

我已經寫了源代碼,如:如何指定QString :: indexOf方法?

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())); 
     } 

} 

的問題是,在我的文本文件中找到的單詞「結束」非常非常頻繁。那麼,有沒有辦法創建一個indexOf方法來搜索「QString s =」start「」之後出現的FIRST「QString e =」end「」?問候

回答

4

的QString的的indexOf的聲明如下:

int QString::indexOf (const QString & str, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const 

如果你看一看,你會看到有一個比你在調用的indexOf使用一個參數。這是因爲它有一個默認值,它是參數:

int from = 0 

這從被默認設置爲0,這樣,只要你ommit這個值的搜索從字符串的開始做,但你可以其值設置爲您在哪裏找到「啓動」二字只是這樣的指標:

int start = x.indexOf(s, 0, Qt::CaseInsensitive); 
int end = x.indexOf(e, start, Qt::CaseInsensitive); //notice the use of start as the 'from' argument 

這樣你會得到的第一個「啓動」二字後到來的第一個「底」字的索引。 希望這有助於!

+0

老實說,我已經有了同樣的想法:D - 只是使用「start + s.length()」而不是「start」。它也有所幫助,但它並沒有解決問題,因爲在QString「開始」出現後仍有許多「終點」。 – Streight 2012-03-07 23:42:17

+0

但是,你不想在「開始」一詞之後出現第一個「結束」單詞嗎?如果你想做的另一件事情只是清楚,看看我們是否可以幫助:) – unbekant 2012-03-07 23:47:37

+0

有沒有辦法與Qt Api做這項工作。因此,我建議你使用循環進行這項工作,例如找到第二個**開始**,然後在那之後找到第二個**結束**。如果你的文本比這種情況更復雜,你必須使用一個詞法分析器(手工編寫的工具)。 – softghost 2012-03-08 08:04:55

0

如果任何人希望實現與模式

BEGIN_WHATEVER_END搜索,是好多了使用下面的正則表達式。

QString TEXT("...YOUR_CONTENT..."); 
QRegExp rx("\\<\\?(.*)\\?\\>"); // match <?whatever?> 
rx.setMinimal(true); // it will stop at the first ocurrence of END (?>) after match BEGIN (<?) 

int pos = 0; // where we are in the string 
int count = 0; // how many we have counted 

while (pos >= 0) {// pos = -1 means there is not another match 

    pos = rx.indexIn(TEXT, pos); // call the method to try match on variable TEXT (QString) 
    if(pos > 0){//if was found something 

     ++count; 
     QString strSomething = rx.cap(1); 
     // cap(0) means all match 
     // cap(1) means the firsrt ocurrence inside brackets 

     pos += strSomething.length(); // now pos start after the last ocurrence 

    } 
}