頭文件:#include <QString>
1、拼接
1)直接使用“+”;
2)append() 在字符串后面添加字符串;
3)prepend() 在字符串前面添加字符串。
QString str1 = "nihao "; QString str2 = "shijie"; QString str3 = ""; str3 = str1 + str2; //nihao shijie str1.append(str2); //nihao shijie
str1.prepend(str2); //"shijienihao "
2、求字符串長度
count(),size(),length()都能返回字符串長度,
注:如果字符串中含有漢字,一個漢字算一個字符。
3、大小寫轉換
toUpper() 轉換為大寫 //str1.toUpper();
tolower() 轉換為小寫 //str2.toLower();
4、去除字符串中的空格
trimmed() 去除字符串首尾的空格
simplified() 去除字符串的首尾空格;並且將中間的連續空格換為一個空格代替。
補充: 去除字符串中的多有字符(結合正則表達式)
str.remove( QRegExp("\\s") );
5、在字符串中查找參數字符串出現的位置
indexOf() 在字符串中查找參數字符串出現的位置
最多指定三個參數:
1、參數字符串; 2、開始匹配位置; 3、指定是否區分大小寫
lastIndexOf() 參數字符串最后出現的位置
6、判斷字符串是否為空
isNull() 和 isEmpty()
QString str1,QString str2=“”;
str1.isNull() //返回true //為賦值字符串
str2.isNull() //返回false //只有“\0”的字符串,也不是Null
str1.isEmpty() //返回 true
str2.isEmpty() //返回 true
注:QString只要賦值就會在最后加上“\0”,因此,在實際使用中常用isEmpty();
7、判斷字符串中是否包含某個字符串
contains()
第一個參數指定字符串,第二個參數指定是否區分大小寫。
8、其他方法
str1.endsWith("cloos",Qt::CaseInsensitive); //判斷字符串是否以某個字符串結尾 str1.startsWith("cloos",Qt::CaseSensitive); //判斷字符串是否以某個字符串開始 str2 = str1.left(3); //返回從字符串左邊取3個字符 str2 = str1.right(3); //返回從字符串右邊取3個字符 str2 = str1.mid(3,4); //返回從字符串左邊第三個字符開始取4個字符。 str2 = str1.section(",",0,3); //從字符串中提取以第一個參數作為分隔符,從0端開始到3端的字符串。
9、與數值之間的轉換
1)轉換為整數
int toInt(bool *ok = Q_NULLPTR, int base=10) const
long toLong(bool *ok = Q_NULLPTR, int base=10) const
short toShort(bool *ok = Q_NULLPTR, int base=10) const
uint toUInt(bool *ok = Q_NULLPTR, int base=10) const
ulong toULong(bool *ok = Q_NULLPTR, int base=10) const
使用方法:
str.toInt(); 第一個參數返回轉換是否成功;第二個參數指定進制,默認為10進制。
2)轉換為浮點數
double toDouble(bool *ok = Q_NULLPTR) const
float toFloat(bool *ok = Q_NULLPTR) const
3)數值轉換為QString
以顯示兩位小數為例
str = QString::number(num,'f',2);
str = QString::asprintf( "%.2",num);
str = str.setNum(num,"f",2);
str = str.sprintf( "%.2", num);