基本操作
QString s1 = "Welcome";
QString s2;
s2 = s1 + "to you";
QString s3 = "Hello ";
s3 = s3 + "World";
qDebug() << s2 << endl << s3 << endl;
QString s4 = "Hello";
s4.append( " World");
qDebug() << s4 << endl;
QString s5;
s5.sprintf("%s","Welcome to my world");
qDebug() << s5 << endl;
QString s6;
s6 = QString("I'm %1 %2").arg("is").arg("Marco");
qDebug() << s6 << endl;
插入
//任意位置
QString s7("Marco good");
s7.insert(6,"is");
qDebug() << s7 << endl;
//開頭
QString s8(" is good");
s8.prepend("Marco");
qDebug() << s8 << endl;
替換
QString s9("Marco is bad");
s9.replace("bad","good");
qDebug() << s9 << endl;
移除字符串兩端空白
QString s10(" Marco is good ");
s10 = s10.trimmed();
qDebug() << s10 << endl;
移除字符串兩端空白並添加一個空白符
QString s11(" Marco is good ");
s11 = s11.simplified();
qDebug() << s11 << endl;
查詢字符串內容
//查詢字符串開頭
QString s12("Welcome to you");
qDebug() << s12.startsWith("Welcome",Qt::CaseSensitive) << " "
<< s12.startsWith("welcome",Qt::CaseInsensitive) << endl;//true
//查詢字符串結尾
qDebug() << s12.endsWith("you",Qt::CaseSensitive) << " "
<< s12.endsWith("You",Qt::CaseInsensitive) << endl;//true
//遍歷整個字符串判斷內容是否出現過
qDebug() << s12.contains("to",Qt::CaseSensitive) << " "
<< s12.contains("To",Qt::CaseInsensitive) << endl;
比較
//localeAwareCompare(const QString& ,const QString &)靜態成員函數
//比較兩個字符串如果前者小於後者返回負整值,等於返回0,大於返回正整數
if(QString::localeAwareCompare(s11,s12) < 0)
qDebug() << "s11 < s12" << endl;
else if(QString::localeAwareCompare(s11,s12) > 0)
qDebug() << "s11 > s12" << endl;
else if(QString::localeAwareCompare(s11,s12) == 0)
qDebug() << "s11 == s12" << endl;
//compare()//該函數可指定是否區分大小寫比較,其他跟localeAwareCompare()類似
if(QString::compare(s11,s12,Qt::CaseSensitive) < 0)
qDebug() << "s11 < s12" << endl;
else if(QString::compare(s11,s12,Qt::CaseSensitive) > 0)
qDebug() << "s11 > s12" << endl;
else if(QString::compare(s11,s12,Qt::CaseSensitive) == 0)
qDebug() << "s11 == s12" << endl;