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

}

问题是,在我的文本文件中经常发现“end”这个词。那么,有没有办法创建一个 indexOf 方法,它只搜索出现在 "QString s = "start" " 之后的第一个 " QString e = "end" " ?问候

4

2 回答 2

7

QString 的 indexOf 的声明如下:

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

如果您看一下,您会发现比您在调用 indexOf 时使用的参数多了一个参数。这是因为它有一个默认值并且它是参数:

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 回答