How do I remove trailing whitespace from a QString?

Di Zou picture Di Zou · Nov 21, 2011 · Viewed 55.1k times · Source

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.

Answer

Frank S. Thomas picture Frank S. Thomas · Nov 21, 2011

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