How do I remove trailing whitespace from a QString?
Asked Answered
I

10

41

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.

Imprecate answered 21/11, 2011 at 16:46 Comment(2)
I think the logic it's flawed: should be while(str.endsWith(' ' ) || str.endsWith( '\n' )) str.chop(1);Palate
@chac, yea it will fail on a string like this: "abc \n \n"Imprecate
P
64

QString has two methods related to trimming whitespace:

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 "";
}
Pudgy answered 21/11, 2011 at 17:41 Comment(5)
Why reinvent the wheel? Use QString::trimmed()Axum
@Axum trimmed removes leading and trailing whitespace while rstrip only removes trailing whitespace.Pudgy
Gotta love how Qt offers some really fancy features yet fails at some of the most basic tasks...2017 and this functionality is still missing.Galvanic
One person's "basic task" is another person's "why would anyone ever need that?"Jennings
Right trimming is pretty much a standard everywhere in modern languages, though.Bisectrix
S
31

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"
Suspensory answered 21/11, 2011 at 16:50 Comment(4)
simplified also combines multiple whitespace INSIDE the stringVaporescence
Yes. Originally I've posted simplified and not trimmed because author mentions removing \n's as well. But anyway, I've updated my answer. Thanks.Suspensory
There is whitespace at the beginning, and I want to keep that whitespace. I also want to keep the whitespace in the middle. I guess I'll have to write my own trimming function. Thanks!Imprecate
In this case I would go with regex'es - easy and elegant. Have a look at skyhisi answer.Suspensory
A
9

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.

Alleviation answered 21/11, 2011 at 16:49 Comment(0)
B
8

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.

Bonucci answered 21/11, 2011 at 17:10 Comment(2)
Simple string operations like indexOf(), left(), strstr() and etc. always faster than regular expressions IMHO.Fatherinlaw
It's not an opinion, it's a fact. For a mundane thing like stripping whitespace, using Regex is relatively very complex (but you may sometimes need regex of course, for complex situations).Croy
M
4

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;
}
Mexico answered 19/5, 2012 at 15:30 Comment(0)
V
3

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.

Vaporescence answered 21/11, 2011 at 16:51 Comment(0)
A
2

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;
}
Adamis answered 7/4, 2013 at 17:37 Comment(0)
E
0

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.

Elsi answered 21/11, 2011 at 16:52 Comment(0)
P
0

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 "";
}
Palate answered 21/11, 2011 at 18:19 Comment(0)
T
0

You can add a non-space char to the begin of the string, trim it, then remove the char

str1=QString("-"+str).trimmed().mid(1);
Teepee answered 22/4, 2021 at 8:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.