6

There's some path as QString:

QString path = "C:/bla/blah/x/y/file.xls";

I thought that maybe getting last offset of / would be a good start. I could then use right method (no pun intended) to get everything after that character:

path = path.right(path.lastIndexOf("/"));

or in a more compatible way:

path = path.right(std::max(path.lastIndexOf("\\"), path.lastIndexOf("/")));

Those both have the same bad result:

ah/x/y/file.xls

What's wrong here? Obviously the path is getting cut too soon, but it's even weirder it's not cut at any of / at all.

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778

2 Answers2

21

The QString method you want is mid, not right (right counts from the end of the string):

path = path.mid(path.lastIndexOf("/"));

mid has a second parameter, but when it's omitted you get the rightmost part of the string.

And for a cleaner / more universal code:

QFileInfo fi("C:/bla/blah/x/y/file.xls");
QString fileName = fi.fileName(); 

NB QFileInfo doesn't query the file system when it doesn't have to, and here it doesn't have to because all the infos are in the string.

Ilya
  • 5,377
  • 2
  • 18
  • 33
1

From QString::right():

"Returns a substring that contains the n rightmost characters of the string."

You're using the index as a count. You'd have to use .size() - .indexOf().

weeska
  • 439
  • 3
  • 7