How can we remove space only from the end of string?



  • ex - @Hello Qt . . .@
    The number of space may vary.



  • There is no build-in rtrimmed or ltrimmed function that I am aware of. So, easiest way is to just create a simple function that does that yourself.

    It could be as simple as (brain to terminal, not tested)
    @
    QString rtrimmed(const QString input)
    {
    QString result = input;
    while (result.count() > 0 && result[result.count()-1)].isSpace() ) {
    result = result.left(result.count() -1 );
    }

    return result;
    }
    @



  • Since trimmed removes also spaces at the beginning, you have to do a loop over each character in your string and then truncate:

    @
    int truncateAt = myString.size();
    for( ; truncateAt > 0; truncateAt-- )
    if( ! QChar.isSpace( myString.at( truncateAt ) )
    break;

    myString.truncate( truncaetAt );
    @

    (forum written code, not tested)



  • I would go with a regex:

    @
    QString ttt = " Qt . . . ab ";
    qDebug() << "ttt" << ttt;
    ttt.replace(QRegExp("\s*$"), "");
    qDebug() << "tt2" << ttt;

    // output:
    // ttt " Qt . . . ab "
    // tt2 " Qt . . . ab"
    @


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.