QString 字符串有如下幾個操作符:
(1) “+” 用於組合兩個字符串,“+=” 用於將一個字符串追加到另一個字符串的末尾,例如:
1 QString str1 = "Welcome";
2 str1 = str1 + "to you !"; //str1 = "Welcome to you!"
3 QString str2 = "Hello,";
4 str2 += "World!"; //str2 = "Hello,World!"
(2)QString::append()函數,具有與“+=”操作符同樣的功能,實現字符串末尾追加另一個字符串,例如:
1 QString str1 = "Welcome ";
2 QString str2 = "to ";
3
4 str1.append(str2); //str1 = "Welcome to "
5 str1.append("you !"); //str1 = "Welcome to you !"
(3)組合字符串的另一個函數是QString::sprintf(),此函數支持的格式定義和C++庫中的函數sprintf()定義一樣,例如:
1 QString str;
2 str.sprintf("%s","Welcome "); //str = "Welcome "
3 str.sprintf("%s"," to you! "); //str = " to you! "
4 str.sprintf("%s %s","Welcome "," to you! "); //str = "Welcome to you! ";
(4)Qt還提供了另一種方便的字符串組合方式,使用QString::arg()函數,此函數的重載可以處理很多的數據類型。此外,一些重載具有額外的參數對字段的寬度、數字基數或者浮點精度進行控制。相對於QString::sprintf(),QString::arg()是一個比較好的解決方案,因爲它類型安全,完全支持Unicode,並且允許改變“/n”參數的順序。例如:
1 QString str;
2 str = QString("%1 was born in %2.").arg("Joy").arg(1993); //str = "Joy was born in 1993.";
其中:
“%1” 被替換爲“Joy”.
"%2"被替換爲“1993”.
(5)QString 也提供了一些其他的組合字符串的方法,包括以下幾種:
a. insert()函數:在原字符串特定位置插入另一個字符
b. prepend()函數:在原字符串開頭插入另一個字符串
c. replace()函數:用指定的字符串去代替原字符串中的某些字符
(6)去除字符串兩端的空白(空白字符包括回車符號“\n”、換行符“\r”、製表符"\t"和空格字符:“ ”等)非常常用,如獲取用戶輸入賬號時就需要去掉空白符。
a. QString::trimmed()函數:移除字符串兩端的空白符
b. QString::simplified()函數:移除字符串兩端的空白字符,使用單個空格字符“ ”代替字符串中出現的空白字符。
(7)字符串比較
比較兩個字符串也是經常使用的功能,QString提供了多種比較手段。
operator<(const QString &);比較一個字符V換是否小於另一個字符串,如果是,則返回true。
operator<=(const QString &);比較一個字符串是否小於等於另一個字符串,如果是,則返回true。
operator==(const QString &);比較兩個字符串是否相等,如果相等,則返回true。
operator>=(const QString &);比較一個字符串是否大於等於另一個字符串,如果是,則返回true
(8)toInt使用實例
QString::toInt()函數將字符串轉換爲整型數值,類似的函數還有toDouble、toFloat()、toLong()、toLongLong()等。下面例子說明其用法:
QString str="125";
bool ok=false;
int hex=str.toInt(&ok,16);//ok=true,hex=293
int dec=str.toInt(&ok,10);//ok=true,dec=125