2

次のようなソースコードを書きました。

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

}

問題は、私のテキストファイルに「終わり」という言葉が非常に頻繁に見られることです。それで、 "QString s = "start" " の後に現れる最初の " QString e = "end" " を検索するだけの indexOf メソッドを作成する方法はありますか? 挨拶

4

2 に答える 2

7

QString の indexOf の宣言は次のとおりです。

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

見てみると、indexOf の呼び出しで使用したものよりも 1 つ多くのパラメーターがあることがわかります。これは、デフォルト値があり、それが引数であるためです。

int from = 0

この from はデフォルトで 0 に設定されているため、この値を省略すると常に文字列の先頭から検索が行われますが、その値を次のように「開始」単語を見つけたインデックスに設定できます。

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

このようにして、最初の「開始」単語の後に続く最初の「終了」単語のインデックスを取得します。お役に立てれば!

于 2012-03-07T23:24:12.207 に答える
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

    }
}
于 2013-06-12T18:02:48.697 に答える