How do I remove trailing whitespace from a QString?

前端 未结 9 1728
甜味超标
甜味超标 2020-12-29 19:24

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

相关标签:
9条回答
  • 2020-12-29 19:33

    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.

    0 讨论(0)
  • 2020-12-29 19:36

    This is a variation of the answer posted by Frank S. Thomas:

    QString rstrip(const QString& str, const char *skip = " \r\n\t") {
      int n = str.size() - 1;
      for (; n >= 0; --n) {
        if (0 == strchr(skip, str.at(n).toAscii()))
          return str.left(n + 1);
      }
      return "";
    }
    
    0 讨论(0)
  • 2020-12-29 19:39

    As far as I know, the only built-in-functions are trimmed() and simplified(). So you will need to trim manually. In that case you should use the QChar function isSpace() to check if a character is a space character.

    0 讨论(0)
  • 2020-12-29 19:40

    QString provides only two trimming-related functions. In case if they don't suit your needs, I'm afraid you need to implement your own custom trimming function.

    QString QString::simplified () const
    Returns a string that has whitespace removed from the start and the end, and that has each sequence of internal whitespace replaced with a single space.

    QString str = "  lots\t of\nwhitespace\r\n ";
    str = str.simplified();
    // str == "lots of whitespace";
    

    QString QString::trimmed () const
    Returns a string that has whitespace removed from the start and the end.

    QString str = "  lots\t of\nwhitespace\r\n ";
    str = str.trimmed();
    // str == "lots\t of\nwhitespace"
    
    0 讨论(0)
  • 2020-12-29 19:47

    If you don't have or don't need any whitespace at the beginning either, you could use QString QString::trimmed () const.

    This ignores any internal whitespace, which is corrected by the alternative solution provided by Andrejs Cainikovs.

    0 讨论(0)
  • 2020-12-29 19: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;
    }
    
    0 讨论(0)
提交回复
热议问题