Search code examples
qtqstring

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


Solution

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