QString remove last characters

Viewed 39914

How to remove /Job from /home/admin/job0/Job

QString name = "/home/admin/job0/Job"

I want to remove last string after"/"

6 Answers

Find last slash with QString::lastIndexOf. After that get substring with QString::left till the position of the last slash occurrence

QString name = "/home/admin/job0/Job";
int pos = name.lastIndexOf(QChar('/'));
qDebug() << name.left(pos);

This will print:

"/home/admin/job0"

You should check int pos for -1 to be sure the slash was found at all.

To include last slash in output add +1 to the founded position

qDebug() << name.left(pos+1);

Will output:

"/home/admin/job0/"

Maybe easiest to understand for later readers would probably be:

QString s("/home/admin/job0/Job");
s.truncate(s.lastIndexOf(QChar('/'));
qDebug() << s;

as the code literaly says what you intended.

You can do something like this:

QString s("/home/admin/job0/Job");
s.remove(QRegularExpression("\\/(?:.(?!\\/))+$"));
// s is "/home/admin/job0" now

If you are using Qt upper than 6 and sure that "/" constains in your word you should use QString::first(qsizetype n) const function instead QString::left(qsizetype n) const

Example:

QString url= "/home/admin/job0/Job"
QString result=url.first(lastIndexOf(QChar('/')));

If you run these code:

QElapsedTimer timer;
timer.start();
for (int j=0; j<10000000; j++)
{
    QString name = "/home/admin/job0/Job";
    int pos = name.lastIndexOf("/");
    name.left(pos);
}
qDebug() << "left method" << timer.elapsed() << "milliseconds";
timer.start();
for (int j=0; j<10000000; j++)
{
    QString name = "/home/admin/job0/Job";
    int pos = name.lastIndexOf(QChar('/'));
    name.first(pos);
}
qDebug() << "frist method" << timer.elapsed() << "milliseconds";

Results:

left method 10034 milliseconds

frist method 8098 milliseconds

sorry for replying to this post after 4 years, but I have (I think) the most efficient answer. You can use

qstr.remove(0, 1); //removes the first character
qstr.remove(1, 1); //removes the last character

Thats everything you have to do, to delete characters ONE BY ONE (first or last) from a QString, until 1 character remains.

Related