Question

Python strings have a function split() that can take a maxsplit argument (from Python docs):

If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

Can QStrings do this? I looked at the docs and there's no split() overload that takes an integer equivalent to maxsplit as argument.

Was it helpful?

Solution

It doesn't seem like it, though it seems to be trivial to implement -

QString str("How are all of you doing");
QStringList list = str.split(' ').mid(0, maxSplit);
QString remainingStr = str.section(' ', maxSplit);
list << remainingStr;

Or if you want to be more performant, you can just copy the code from QString::split, and add the extra feature. The code is there at qtbase/src/corelib/tools/qstring.cpp. You just need to add && list.size() <= maxSplit in the while loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top