1.QString提供了一个二元的 "+" 操作符用于组合两个字符串,并且提供了一个 "+=" 的操作符用于将一个字符串追加到另一个字符串的末尾,列如:
QString str1 = "Welcome ";
str1 = str1+"to you "; //str1 = "Welcome to you";
QString str2 = "hellow ";
str2 += "world "; //str2 = "hellow world ";
2.QString::append()函数具有与"+="操作符相同的功能,实现在一个字符串的末尾添加另一个字符串,例如:
QString str1 = "hello ";
QString str2 = "girl ";
str1.append(str2); //str1 = "hello girl ";
str1.append("hei hei "); //str1 = "hello girl hei hei";
3.组合字符串的另一个函数是QString::sprintf(),此函数支持的格式定义符和C++库中的函数sprintf()定义的一样。列如:
QString str;
str.sprintf("%s"," Welcome "); //str = " Welcome ";
str.sprintf("%s"," to you "); //str = " to you ";
str.sprintf("%s%s","Welcome ","to you "); //str = "Welcom to you"
这里需要注意后面字符串是什么样str就是什么样
4.Qt还提供了另一种方便的字符串组合方式,使用QString::arg()函数,此函数的重载可以处理很多的数据类型。此外,一些重载具有额外的参数对字段的宽度、数字基数或者浮点数精度进行控制。通常,相对与函数QString::sprintf(),函数QString::arg()是一个比较好的解决方案,因为它类型安全,完全支持Unicode,并且允许改变"%n"参数的顺序。列如:
QString str;
str = QString("%1 was born %2").arg("John").arg("1970"); //str = "John was born 1970"
%1被替换John
%2被替换1970
5.QString也提供了一些其他组合字符串的方法,包括如下几种。
insert()函数:在原字符串特定的位置插入另一个字符串
prepend()函数:在原字符串的开头插入另一个字符串
replace()函数:用指定的字符串代替原字符串中的某些字符
6.很多时候去掉一个字符串两端的空白(空白字符串包括回车字符"\n"、换行字符"\r"、制表符"\t"、和空格符" "等)非常有用,如获取用户输入的账号时
QString::trimmed()函数:移除字符串两端的空白字符
QString::simplified()函数:移除字符串两端的空白字符,然后使用单个空格字符“ ”替代原来空白字符串
QString str = " Welcome \t to \t you ";
str = str.trimmed(); //str = "Welcome \t to \t you";
str = str.simplified(); //str = "Welcome to you"
查询字符串数据
函数QString::startsWith()用法,判断指定字符串是否为字符串开头部分
函数QString::endsWith()用法,判断指定字符串是否为字符串结尾部分
函数QString::contains()用法,判断是否包含指定字符
QString str = "Welcome to you ";
//此函数两个参数,第一个参数指定了一个字符串,第二个参数指定是否大小写敏感(默认大小写是敏感的)
str.startsWith("Wel",Qt::CaseSensitive); //返回true
str.startsWith("you",Qt::CaseSensitive); //返回false
//此函数用于判断一个字符串是否为某个字符串的结尾部分
str.endsWith("you",Qt::CaseSensitive); //返回false,如果字符串是"you "则返回true
//此函数用于判断指定字符串是否在字符串里面出现过
str.contains("to",Qt::CaseSensitive); //返回true
比较两个字符串,QString提供了多种比较功能
1.operator<(const QString &):比较一个字符串是否小于另一个字符串,如果是则返回true。
2.operator<=(const QString &):比较一个字符串是否小于或者等于另一个字符串
3.operator==(const QString &):比较两个字符串是否相等
4.operator>=(const QString &):比较一个字符串是否大于或等于另一个字符串
字符串的转换
QString::toInt()函数将字符串转换成整数数值,类似的函数还有toDouble()、toFloat()、toLong()、toLongLong()等
QString str = "125";
bool ok;
int dec = str.toInt(&ok,10); //第一个参数是一个bool类型指针,用于返回转换的状态,
int hex = str.toInt(&ok,16); //转换成功时设置为true,第二个参数指定转换基数
字符串替换
// 采用QRegExp正则表达式
QString str1 = "2017-06-20";
// 使用空格替换"/"
QString str2 = str1.replace(QRegExp("\\-"), "/");