How do I remove trailing whitespace from a QString?

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 "";
}

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.


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.


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"

Tags:

C++

String

Qt

Trim

Qt4