QT中字串的比較 查詢 替換等操作

2021-10-03 22:06:41 字數 2748 閱讀 2571

基本操作

qstring s1 = "welcome";

qstring s2;

s2 = s1 + "to you";

qstring s3 = "hello ";

s3 = s3 + "world";

qdebug() << s2 << endl << s3 << endl;

qstring s4 = "hello";

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;

字串的比較 查詢 替換

1 public boolean equals object anobject 區分大小寫的比較 2 public boolean equalsignorecase string anotherstring 不區分大小寫的比較 3 public nt compareto string another...

qt 字串比較

在qt中經常會使用到字串的比較,這裡的比較不僅是數字和字母還包含漢字的字元。下面是幾種常用的字元比較方式 qstring str1 你好 qstring str3 ui pushbutton 13 text 1 qstring compare str1,str3 2 qstring compare ...

字串 字串的查詢和替換

hello str hello world 1.判斷是否以指定字串開始 print hello str.startswith hello 2.判斷是否以指定字串結束 print hello str.endswith world 3.查詢指定字串 index同樣可以查詢指定的字串在大字串中的索引 pr...