How to specify the QString::indexOf method not to be sensitive to the number of spaces between two words?
Question
I have written a source code like:
int main(int argc, char *argv[]) {
QFile File (directory + "/File");
if(File.open(QIODevice::ReadOnly | QIODevice::Text))
{
QTextStream Stream (&File);
QString FileText;
do
{
FileText = Stream.readLine();
QString s = "start";
QString e = "end here";
int start = FileText.indexOf(s, 0, Qt::CaseInsensitive);
int end = FileText.indexOf(e, Qt::CaseInsensitive);
if(start != -1){ // we found it
QString y = FileText.mid(start + s.length(), (end - (start + s.length())));
qDebug() << y << (start + s.length()) << (end - (start + s.length()));
}
}
My problem here is, that the int end = FileText.indexOf(e, Qt::CaseInsensitive);
with QString e = "end here";
is just found when there are exactly three spaces between the word "end" and "here". This is problematical, because in the text I read the spaces between these two words will surely differ from time to time. Furthermore I need to write both words "end" and "here". I tried to reduce the problem to the basis and hope someone has an idea/solution.
Solution
Reduce the number of inter-spaces to 1 using QString::simplified()
method.
OTHER TIPS
You could also try QRegExp:
#include <QDebug>
#include <QString>
#include <QRegExp>
int main()
{
QString text("start ABCDE1234?!-: end here foo bar");
// create regular expression
QRegExp rx("start\\s+(.+)\\s+end\\s+here", Qt::CaseInsensitive);
int pos=0;
// look for possible matches
while ((pos=rx.indexIn(text, pos)) != -1) {
qDebug() << rx.cap(1); // get first match in (.+)
pos+=rx.matchedLength();
}
return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow