PDA

View Full Version : better way to get index of substring?



tuli
17th February 2019, 10:04
Hey,

I find myself often needing to find the index of a substring *after* the substring.
So I end up with this pattern a lot:



str.left(std.indexOf("something") + strlen("something"))

or


str.left(std.indexOf("something") + 9)


In one case I have to count chars by hand, in the other I have to duplicate the string.


Is there a better way to do it?

anda_skoa
17th February 2019, 13:55
Well, duplication is only necessary because you don't have the substring in a variable.



const QString substring("something");
str.left(str.indexOf(substring) + substring.length());


Alternatively, a regular expression match could be used to extract the result. Something like


QRegularExpression pattern("^(.*)something"); // any characters from the beginning of the string until "something"

QRegularExpressionMatch match = pattern.match(str);
if (match.hasMatch()) {
// result in match.captured(1);
}

Probably only worth though it if the you look for the same pattern in a lot of string.

Cheers,
_