Question

How do I get value "Recording.mp3" from this QString

C:/Users/Admin/AppData/Local/Temp/AudelloTemp/Recording.mp3

If I use lastIndexof('/') function then it searches backward for last occurrence

If I use indexof('/') function then it searches forward for first occurrence.

I am not getting any way to get it.

Or is the only way to use a loop to get that value?

Was it helpful?

Solution

Seeing as it's a file path and you're looking for the file name, the correct approach would be this:

// When you have this:
QString s("C:/Users/Admin/AppData/Local/Temp/AudelloTemp/Recording.mp3");

// Do this:

QFileInfo f(s);
QString s1 = f.fileName();
// now s1 is "Recording.mp3"

Nevertheless, to answer your question as worded, the QString member function to use would be lastIndexOf(). You've misread the documentation: it doesn't "search backward for the last occurrence," it "looks for the last occurrence in the string, doing it by searching backwards." So in your case, it would indeed return the / separating AudelloTemp from Recording.mp3.

OTHER TIPS

How about:

QString filename_only(const QString& path)
{
  int index = path.lastIndexOf('/'); // check validity
  return path.right(path.size() - index); // Might be off by one, feel free to fix
}

I don't have Qt here now, so please check if I'm off-by-one.

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