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.

1
  • 8
    QFileInfo( "C:/bla/blah/x/y/file.xls" ).fileName();. Commented Mar 14, 2016 at 13:03

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.