Searching for the last substring after "\"
-
Hi,
Fo example, I have the directory "C:\examples\toys\vehicles\cars".
What would you suggest to use to get the substring "cars" ?
Any function in QDir or QString ?Many thanks
-
Sounds like QDir::dirName is pretty much what you want.
-
There are several ways to do so.
One way could be to split the string with QString::split() which will return a QStringList. QStringList::last() will give you then the last element of this list, (you should check the size of the list if its >0)
-
Finally I use lastIndexOf on the QString to get the position of the last ""
-
@mulfycrowh said:
Finally I use lastIndexOf on the QString to get the position of the last ""
In case of you are dealing with file system paths I strongly recommend using
QDir::dirName
. It has been purposely-designed for that task.
Your method will already stop working if the system you're running on uses a different file path separator. You could useQDir::Separator()
and still use your method of extracting but you might hit other problems down the track in the future. -
QString
has a specialized function exactly for this kind of task (works for any string and separator, not only paths): section():QString path("C:\\examples\\toys\\vehicles\\cars"); QString last_part = path.section('\\', -1);
@the_ Please don't ever use
split()
for things like this. It creates a dynamically allocated linked list of dynamically allocated copies of parts of the string and then copies the last one. That's probably the slowest and most memory consuming way to do this. -
Thanks. It runs perfectly
-
If you're not going to use
QDir::dirName()
please at least useQDir::Separator()
in yourQString::section()
function. Do yourself a favor :)
Otherwise it won't work on any system that uses a separator other than\
(which is almost every system except Windows). -
I mean with dirName