C++ 如何从 QString 中删除尾随空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8215303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:11:26  来源:igfitidea点击:

How do I remove trailing whitespace from a QString?

c++stringqtqt4trim

提问by Di Zou

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.

我想删除QString. 我正在寻找str.rstrip()使用QString.

I did some Googling, and found this: http://www.qtforum.org/article/20798/how-to-strip-trailing-whitespace-from-qstring.html

我做了一些谷歌搜索,发现了这个: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.

有没有更简单的方法来做到这一点?我想在开始时保留所有空格。

回答by Frank S. Thomas

QStringhas two methods related to trimming whitespace:

QString有两种与修剪空格相关的方法:

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:

如果您只想删除尾随空格,则需要自己实现。这是一个模仿以下实现的实现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 "";
}

回答by Andrejs Cainikovs

QStringprovides 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 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::simplified () const
返回一个字符串,该字符串从开头和结尾删除了空格,并将每个内部空格序列替换为一个空格。

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 QString::trimmed () const
返回从开头和结尾删除空格的字符串。

QString str = "  lots\t of\nwhitespace\r\n ";
str = str.trimmed();
// str == "lots\t of\nwhitespace"

回答by Bart

If you don't have or don't need any whitespace at the beginning either, you could use QString QString::trimmed () const.

如果您在开头也没有或不需要任何空格,则可以使用QString QString::trimmed () const.

This ignores any internal whitespace, which is corrected by the alternative solution provided by Andrejs Cainikovs.

这会忽略任何内部空白,这已由 Andrejs Cainikovs 提供的替代解决方案纠正。

回答by Silas Parker

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.

这是否会更快,我不确定。

回答by Martin Beckett

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.

QString::Trimmed()从开头和结尾删除空格 - 如果您确定开头没有空格,则可以使用它。

回答by Johan

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

回答by Jason C

No deep copy and no repeated calls to size/chop:

没有深度复制,也没有重复调用 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;
}

回答by CapelliC

This is a variation of the answer posted by Frank S. Thomas:

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

回答by Sebastian Negraszus

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 QCharfunction isSpace()to check if a character is a space character.

据我所知,唯一的内置函数是trimmed()and simplified()。所以你需要手动修剪。在这种情况下,您应该使用该QChar函数isSpace()来检查字符是否为空格字符。