Sijith
Sijith

Reputation: 3922

QString remove last characters

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

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

I want to remove last string after"/"

Upvotes: 14

Views: 57377

Answers (6)

user10609288
user10609288

Reputation:

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

Upvotes: -1

Sucharek
Sucharek

Reputation: 1

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.

Upvotes: -2

mekkanizer
mekkanizer

Reputation: 741

You have QString::chop() for the case when you already know how many characters to remove.
It is same as QString::remove(), just works from the back of string.

Upvotes: 23

transistor
transistor

Reputation: 669

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.

Upvotes: 6

vahancho
vahancho

Reputation: 21220

You can do something like this:

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

Upvotes: 1

Xplatforms
Xplatforms

Reputation: 2232

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/"

Upvotes: 19

Related Questions