Qt中的字符串類 QString類 保存了16位Unicode值,提供了豐富的操作、查詢和轉換等函數。
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()函數:移除字符串兩端的空白字符,使用單個空格字符“ ”代替字符串中出現的空白字符。
例如:
1 QString str1 = " Welcome \t to \n you! "; 2 QString str2 = " Welcome \t to \n you! "; 3 str1 = str1.trimmed(); // str1 = " Welcome \t to \n you! " 4 str2 = str2.simplified(); // str2 = " Welcome to you ! "