如何指定QString :: indexOf方法?

时间:2012-03-07 23:06:30

标签: c++ qt indexof qstring

我写了一个源代码,如:

    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“”?问候

2 个答案:

答案 0 :(得分:5)

QString的indexOf声明如下:

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

如果您看一下,您会看到还有一个参数,而不是您在indexOf调用中使用的参数。这是因为它有一个默认值,它是参数:

int from = 0

默认情况下,此from设置为0,因此每当您省略此值时,搜索都是从字符串的开头进行的,但您可以将其值设置为您找到“start”字的索引,如下所示:

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

通过这种方式,您将获得第一个“开始”单词后面的第一个“结束”单词的索引。 希望这有帮助!

答案 1 :(得分: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

    }
}