QString類常用函數

 

        QT的QString類是一個常用類,提供了很方便的對字符串操作的接口。

        最近老是用到這個類,就總結了一下QString類的常用函數,例:

        1、

                QString str1 = "hello world!";

 

                //獲取字符串的長度

                str1.length();        //=5

                //從最左邊開始截取兩個字符

                str1.left(2);          //=he

                /從最右邊開始截取兩個字符

                str1.right(2);       //=d!

                //截取字符串,第一個參數是起始位置,第二個參數是長度

                str1.mid(3, 2);     //=lo

                //在字符串末尾添加字符

                str1.append("haha");        //=hello world!haha

        2、

                QString str2 = " hello , world ! ";        //有五個空格

 

                //去掉字符串首尾的空格

                str2.trimmed();           //=hello , world !

                //移除字符串中的某個字符

                str2.remove(" ");        //=hello,world!

        3、

                //格式化字符串輸出,其中的%1等爲佔位符

                QString str3 = QString("%1 %2 (%3--%4)").arg("hello").arg("world").arg(100).arg(500);

                //str3 = hello world (100--500)

 

        4、分割字符串

                QString str = "a;b;c;";

                QStringList strList = str.split(";");

                QString result1 = strList.at(0);   //=a        

                QString result2 = strList.at(1);   //=b

                QString result3 = strList.at(2);   //=c

                QString result4 = strList.at(3);   //=""

 

        5、轉換函數:

                ① toAscii():返回一個ASCII編碼的8位字符串;                

                ② toLatin1():返回一個Latin-1(ISO8859-1)編碼的8位字符串;

                ③ toUtf8():返回一個UTF-8編碼的8位字符串(UTF-8是ASCII碼的超級,它支持整個Unicode字符集);

              

                ④ toLocal8Bit():返回一個系統本地(locale)編碼的8位字符串。

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章