Reputation: 861
I have written a source code like:
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()));
}
}
The problem is, that in my textfile the word "end" is found very very often. So, is there a way to create a indexOf method that just searchs for the FIRST " QString e = "end" " that appears after the "QString s = "start" " ? greetings
Upvotes: 3
Views: 20263
Reputation: 1140
If anyone else wants to implement a search with pattern
BEGIN_WHATEVER_END, is so much better use the following Regex.
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
}
}
Upvotes: 0
Reputation: 1555
The declaration of indexOf of QString is the following:
int QString::indexOf ( const QString & str, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
If you take a look you'll see that there is one more parameter than the one you use in your call to indexOf. This is because it has a default value and it is the argument:
int from = 0
This from is by default set to 0 so that whenever you ommit this value the search is done from the beginning of the string, but you can set its value to the index where you found the "start" word just like this:
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
This way you are going to get the index of the first "end" word that comes after the first "start" word. Hope this helps!
Upvotes: 10