How do I remove trailing whitespace from a QString

2019-02-11 16:19发布

I want to remove all the trailing whitespace characters in a QString. I am looking to do what the Python function str.rstrip() with a QString.

I did some Googling, and found this: http://www.qtforum.org/article/20798/how-to-strip-trailing-whitespace-from-qstring.html

So what I have right now is something like this:

while(str.endsWith( ' ' )) str.chop(1);
while(str.endsWith( '\n' )) str.chop(1);

Is there a simpler way to do this? I want to keep all the whitespace at the beginning.

9条回答
地球回转人心会变
2楼-- · 2019-02-11 16:36

QString::Trimmed() removes whitespace from the start and the end - if you are sure there is no whitespace at the start you can use this.

查看更多
老娘就宠你
3楼-- · 2019-02-11 16:39

You can do it with a regexp:

#include <QtCore>

int main(int argc, char** argv)
{
    QCoreApplication app(argc, argv);

    QString str("Hello world    ");

    qDebug() << str;

    str.remove(QRegExp("\\s+$"));

    qDebug() << str;

    return 0;
}

Whether this would be faster, I'm not sure.

查看更多
走好不送
4楼-- · 2019-02-11 16:47

If you don't want to make a deep copy of the string:

QString & rtrim( QString & str ) {
  while( str.size() > 0 && str.at( str.size() - 1 ).isSpace() )
    str.chop( 1 );
  return str;
}
查看更多
登录 后发表回答