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位字符串。

 

 

 

 

 

 

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