Qt中的字符串类
Qt中的字符串类
一. QString类的特点
- 采用Unicode编码
- 使用隐式共享技术来节省内存和不必要的数据拷贝
- 跨平台使用,不必考虑字符串的平台兼容性
二. QString类的一些使用方法
-
定义、赋初值和打印
void test1() { QString s1("hello"); QString s2= " world"; QString s3 = s1+s2; QString s4 = "にいはお"; qDebug() << s1; qDebug() << s2; qDebug() << s3; qDebug() << s4; }
17:16:46: Starting E:\QTest\build-3-QString-Desktop_Qt_5_14_2_MinGW_64_bit-Debug\debug\3-QString.exe ... "hello" " world" "hello world" "にいはお"
-
追加、拼接
void test2() { QString s1("hello"); QString s2= " world"; QString s3 = s1+s2; QString s4 = "にいはお"; qDebug() << s1; s1.append(s2); //s1向后追加s2的内容 "hello world" qDebug() << s1; s2.prepend(s4); //s2前面拼接字符串s4 "にいはお world" qDebug() << s2; qDebug() << s3; qDebug() << s4; }
17:23:10: Starting E:\QTest\build-3-QString-Desktop_Qt_5_14_2_MinGW_64_bit-Debug\debug\3-QString.exe ... "hello" "hello world" "にいはお world" "hello world" "にいはお"
-
查找字符、子串、修剪字符串
void test3() { QString s1("hello Andrea"); QString s2= "你好 二莹子"; QString s3 = " にいはお えんちゃん"; qDebug() << s1.indexOf(" "); //indexOf()这个方法可以返回字符串中某个字符的下标位置 qDebug() << s1[s1.indexOf(" ")]; //字符串可以直接下标访问某个字符,这里验证一下上面的indexOf()的准确性 qDebug() << s2.mid(s2.indexOf(" ")+1, s2.length()); //mid(起始位置的下标,结束位置的下标)这个方法,可以获取字符串中的子串,这句话的功能是获取到s2这个字符串中"二莹子"这个字符串 qDebug() << s3; s3 = s3.trimmed(); //将起始位置的空格删除 qDebug() << s3; }
17:40:12: Starting E:\QTest\build-3-QString-Desktop_Qt_5_14_2_MinGW_64_bit-Debug\debug\3-QString.exe ... 5 ' ' "二莹子" " にいはお えんちゃん" "にいはお えんちゃん"
三. QString的使用注意事项
- 在QString的构造函数中有如下的描述
- 编辑器要设置成UTF-8的编码格式,这样给QString传递内容的时候,数据才显示正常,代码才能通过编译。
编辑区域右上角选择编辑器的编码格式,选择UTF-8后点击按编码格式保存