23

I have these url strings

file:///home/we/Pictures/neededWord/3193_n.jpg

file:///home/smes/Pictures/neededWord/jds_22.png

file:///home/seede/kkske/Pictures/neededWord/3193_n.jpg

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?

Wazery
  • 15,394
  • 19
  • 63
  • 95

4 Answers4

45

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.

Chris
  • 17,119
  • 5
  • 57
  • 60
1

I fixed it this way:

QStringList splitted = info.url().prettyUrl().split("/");
*header   = splitted.at(splitted.findIndex(splitted.last()) - 1);
Wazery
  • 15,394
  • 19
  • 63
  • 95
  • 2
    Why do you need to search for the last item? You know what it's index is already the same way you know the first item is at index 0. This is a **very** strange way to go about something so simple. – Chris Aug 01 '12 at 14:12
1

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);
Martin Hennings
  • 16,418
  • 9
  • 48
  • 68
0

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.setMinimal(false);
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!

sadjoker
  • 14
  • 1