1. 程式人生 > >Qt程式設計中如何去掉字串中多餘的空格

Qt程式設計中如何去掉字串中多餘的空格

一,自己建立函式解決        

void deBlank(QString &strs)
{
    int len = strs.length();
    for (int i=0;i<len;i++)
    {
        if (strs.at(i).isSpace())
        {
            strs[i] = QChar(' ');
        }
    }
}

用法:QString str(“a b        c”);

str = deBlank(str);

經過轉換後str的內容就為"a b c”。

二,利用Qt中自帶的函式解決

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.

Whitespace means any character for which 

QChar::isSpace() returns true. This includes the ASCII characters '\t', '\n', '\v', '\f', '\r', and ' '.

Example:

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