Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

c++ - How do I remove trailing whitespace from a QString?

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( '
' )) str.chop(1);

Is there a simpler way to do this? I want to keep all the whitespace at the beginning.

question from:https://stackoverflow.com/questions/8215303/how-do-i-remove-trailing-whitespace-from-a-qstring

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...