How do I remove trailing whitespace from a QString?

前端 未结 9 1729
甜味超标
甜味超标 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:48

    No deep copy and no repeated calls to size/chop:

    QString & rtrimInPlace (QString &str) {
        for (int n = str.size() - 1; n >= 0; -- n)
            if (!str.at(n).isSpace()) {
                str.truncate(n + 1);
                break;
            }
        return str;
    }
    
    0 讨论(0)
  • 2020-12-29 19:51

    QString has two methods related to trimming whitespace:

    • QString QString::trimmed() const
      Returns a string that has whitespace removed from the start and the end.
    • 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.

    If you want to remove only trailing whitespace, you need to implement that yourself. Here is such an implementation which mimics the implementation of trimmed:

    QString rstrip(const QString& str) {
      int n = str.size() - 1;
      for (; n >= 0; --n) {
        if (!str.at(n).isSpace()) {
          return str.left(n + 1);
        }
      }
      return "";
    }
    
    0 讨论(0)
  • 2020-12-29 19:57

    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.

    0 讨论(0)
提交回复
热议问题