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.
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.
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
:This is a variation of the answer posted by Frank S. Thomas:
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 QString::trimmed () const
Returns a string that has whitespace removed from the start and the end.
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.
No deep copy and no repeated calls to size/chop: