QString的解析与常用功能

QString存储一个16位QChar字符串,其中每个QChar对应一个UTF-16代码单元。(编码值大于65535的Unicode字符使用代理对存储,即两个连续的qchar。)
Unicode是一个国际标准,支持目前使用的大多数书写系统。它是US-ASCII (ANSI X3.4-1986)和Latin-1 (ISO 8859-1)的超集,
并且所有US-ASCII/Latin-1字符都在相同的代码位置上可用。

在这里插入图片描述

QString是QT编程中常用的类,除了用作数字量的输入输出外,QString还有很多其它功能,熟悉这些常见的功能,有助于灵活地实现字符串的处理功能。
QString存储字符串采用的是Unicode码,每一个字符是一个16位的QChar,而不是8位的char,所以QString处理中文字符没有问题,而且一个汉字算一个字符。

1、append和prepend

append()在字符串的后面添加字符串,prepend()在字符串的前面添加字符串,如:

QString str1="a", str2="b";
str1.append(str2); //ab

2、toUpper()和toLower()
toUpper()将字符串内的字母全部转换为大写形式,toLower()将字母全部转换为小写形式,如:

QString str1 = "Hello, World", str2;
str2 = str1.toUpper(); //str2 = "HELLO, WORLD";

3、count()、size()、length()

count()、size()、length()都返回字符串的个数,这3个函数是相同的,但是要注意,字符串中如果有汉字,一个汉字算一个字符。

QString str1 = "NI 好";
int N = str1.count(); //N=3
int N = str1.size();//N=3
int N=str1.length(); //N=3

4、trimmed()和simplified()

trimmed()去掉字符串首尾的空格,simplified()不仅去掉首尾的空格,中间连续的空格也用一个空格替换。

QString str1 = " Are       you ok?  ", str2;
str2 = str1.trimmed(); //str2="Are     you OK?"
str2=str1.simplified();//str2="Are you OK?"

5、indexOf()和lastIndexOf()

indexOf()的函数原型为:
int indexOf(const QString &str, int form = 0, Qt::CaseSensitivity cs = Qt::caseSensitive) const
其功能是在自身字符串内查的参数字符串str出现的位置,参数from是开始查找的位置,QtLLCaseSensitivity cs参数指定是否区分大小写。
lastIndexOf()函数则是查的某个字符中最后出现的位置。

QString str1="my name is xiaoming";
int N=str1.indexOf("name"); //N=3

6、isNull()和isEmpty()

两个函数都是判读字符串是否为空,但是稍有差别。如果一个空字符串,只有"\0",isNull()返回false,而isEmpty()返回true; 只有未赋值的字符串,isNull才返回true.

QString str1,str2="";
bool N = str1.isNull();//N=true 未赋值的字符串变量
bool N= str2.isNull();//N=false 只有"\0"的字符串,也不是NULL
bool N=str1.isEmpty(); //N=true
bool N=str2.isEmpty(); //N=true

QString只要赋值,就在字符串的末尾自动加上"\0",所以,如果只是要判断字符中的内容是否为空,常用isEmpty().

7、contains()

判断字符串内是不包含某个字符串,可以指定是否区分大小写。

QString str1 = "test.cpp";
N=str1.contains(".cpp", Qt::CaseInsensitve);//N=true,不区分大小写
N=str1.contains(".CPP", Qt::CaseSensitive);//N=false,区分大小写

8、endsWith()和startsWith()

startsWith()判断是否以某个字符串开头,endWith()判断是否以某个字符结束。

QString str1="test.cpp";
N=str1.endsWith("cpp", Qt::CaseInsensitive);//N=true,不区分大小写
N=str1.startsWith("TEST"); //N=true, 缺省不区分大小写

9、left()和right()

left表示从字符串取左边多少个字符;right表示从字符串中取右边多少个字符。注意汉字被当作一个字符。

QString str2,str1="我的名字是";
str2 = str1.left(1);//str1="我"

10、section()

section()的函数原型为:
QString section(const QString &sep, int start, int end=-1, SectionFlags flags=SectionDefault) const
其功能是从字符串中提取以sep作为分隔符,从start端到end端的字符串。

QString str2,str1="数学,语文";
str2 = str1.section(",", 0,0) ; //str2="数字" 第一段的编号为0
str2= str1.section(",", 0, 1); //str2="数学,语文"

猜你喜欢

转载自blog.csdn.net/maokexu123/article/details/130555622
今日推荐