一、拼接字符串
拼接字符串有兩種方法: += 、 append
QString s; s = "hello"; s = s + " "; s += "world"; qDebug() << s; // "hello world"
QString s1 = "hello" ; QString s2 = "world" ; s1.append(" "); s1.append(s2); qDebug() << s1; // "hello world"
二、格式化字符串
格式化字符串的使用方法和Python的差不多,都是比較簡單的,也是有兩種方法: sprintf() 、 arg()
QString s1, s2; s1.sprintf("%s", "hello"); s2.sprintf("%s %s", "hello", "world"); qDebug() << s1; // "hello" qDebug() << s2; // "hello world"
QString s1; s1 = QString("My name is %1, age %2").arg("zhangsan").arg(18); qDebug() << s1; // "My name is zhangsan, age 18"
三、編輯字符串
處理字符串的方法有種:
insert() 在原字符串特定位置插入另一個字符串
QString s = "hello"; s.insert(0, "aa"); qDebug() << s; // "aahello"
prepend() 在原字符串開頭位置插入另一個字符串
QString s = "hello"; s.prepend("abc_"); qDebug() << s; // "abc_hello"
replace() 用指定的字符串替代原字符串中的某些字符
QString s = "hello"; s.replace(0, 3, "a"); // 0-3的字符替換成a qDebug() << s; // "alo"
trimmed() simplified() 移除字符串兩端的空白字符
QString s = " hello"; s = s.trimmed(); qDebug() << s; // "hello"
四、判斷
startsWith() 判斷字符串是否以某個字符開頭
endsWith() 判斷字符串是否以某個字符結尾
QString s = "hello"; // true,大小寫不敏感 qDebug() << s.startsWith("H", Qt::CaseInsensitive); // true,大小寫敏感 qDebug() << s.startsWith("h", Qt::CaseSensitive);
isNull() isEmpty() 字符串判空
qDebug() << QString().isNull(); // true qDebug() << QString().isEmpty(); // true qDebug() << QString("").isNull(); // false qDebug() << QString("").isEmpty(); // true
五、字符串間比較
operator<(const QString&) // 字符串小於另一個字符串,true operator<=(const QString&) // 字符串小於等於另一個字符串,true operator==(const QString&) // 兩個字符串相等,true operator>=(const QString&) // 字符串大於等於另一個字符串,true // 比較兩個字符串,返回數字 localeAwareCompare(const QString&, const QStriing&) // 加入了大小寫是否敏感參數,返回數字 compare(const QString&, const QString&, Qt::CaseSensitivity)
六、字符串格式轉換
toInt() // 轉整形 toDouble() // 轉雙進度浮點數 toFloat() // 轉單精度浮點數 toLong() // 轉長整型 toLongLong() // 轉長長整形 toAscii() // 返回一個ASCII編碼的8位字符串 toLatin1() // 返回一個Latin-1(ISO8859-1)編碼的8位字符串 toUtf8() // 返回一個UTF8編碼的8位字符串 toLocal8Bit() // 返回一個系統本地編碼的8位字符串