QString Splitting

I have these url strings




I want to extract the "neededWord" from each of them. As it appears from them, the name of the image is always after the "neededWord" and the changing part in the string is before the "neededWord". The way I thought of is to split the string using the "/" seperator from right and take the second element in the resulted QstringList. So how to split from right, or is there a better way to do that?


Well you would just take the second to last element:

QStringList pieces = url.split( "/" );
QString neededWord = pieces.value( pieces.length() - 2 );

Alternatively, you could use a regular expression.

I fixed it this way:

QStringList splitted = info.url().prettyUrl().split("/");
*header   = splitted.at(splitted.findIndex(splitted.last()) - 1);

Or something like this from the top of my head(not tested):

QString neededWord = "";
QString str = "file:///home/seede/kkske/Pictures/neededWord/3193_n.jpg";
QRegExp rx(".*Pictures\\/(\\w+)\\/.*(?:jpg|png|gif|bmp|tiff)");
rx.setCaseSensitivity(Qt::CaseSensitive) // or use Qt::CaseInsensitive
if (rx.indexIn(str) != -1) {
     neededWord = rx.cap(1);

"neededWord" should be in neededWord QString. Regexp pattern can be refined and written in more elegant way but i hate writing those :) even if they are super useful!

I would use QString::lastIndexOf() together with QString::mid() to prevent unnecessary QString / QStringList creation and destruction:

// Example:
//  0         1         2         3         4         5
//  012345678901234567890123456789012345678901234567890
// "file:///home/we/Pictures/neededWord/3193_n.jpg"

QString neededWord;
int const lastSlash = url.lastIndexOf('/'); // := 35
int const prevSlash = url.lastIndexOf('/', -lastSlash - 1); // := 24
if(lastSlash > prevSlash + 1 && prevSlash >= 0) {
    neededWord = url.mid(prevSlash, lastSlash - prevSlash - 1); // len := 10

Depending on your needs you can optimize this even further by using a QStringRef:

QStringRef neededWordRef(&url, prevSlash, lastSlash - prevSlash - 1);

Need Your Help

Declaring static constants in ES6 classes?

javascript class constants ecmascript-6

I want to implement constants in a class, because that's where it makes sense to locate them in the code.

Fragment shared element transitions don't work with ViewPager

android android-viewpager android-transitions

My app contains a view which consists of a ViewPager consisting of a handful of fragments. When you click on an item in one of these fragments, the expected behavior is for the shared element (in t...