Qt数据结构-QString一:常用方法

 

一、拼接字符串

拼接字符串有两种方法: +=  、  append

QString s;
s = "hello";
s = s + " ";
s += "world";
qDebug() << s;  // "hello world"
QString s1 = "hello" ;
QString s2 = "world" ;

s1.append(" ");
s1.append(s2);
qDebug() << s1;   // "hello world"

 

 

二、格式化字符串

格式化字符串的使用方法和Python的差不多,都是比较简单的,也是有两种方法: sprintf()     、  arg()

QString s1, s2;
s1.sprintf("%s", "hello");
s2.sprintf("%s %s", "hello", "world");

qDebug() << s1;    // "hello"
qDebug() << s2;    // "hello world"
QString s1;
s1 = QString("My name is %1, age %2").arg("zhangsan").arg(18);

qDebug() << s1;  // "My name is zhangsan, age 18"

 

 

 

三、编辑字符串

处理字符串的方法有种:

insert() 在原字符串特定位置插入另一个字符串

QString s = "hello";
s.insert(0, "aa");

qDebug() << s;  // "aahello"

 

prepend() 在原字符串开头位置插入另一个字符串

QString s = "hello";
s.prepend("abc_");

qDebug() << s; // "abc_hello"

 

replace() 用指定的字符串替代原字符串中的某些字符

QString s = "hello";
s.replace(0, 3, "a");  // 0-3的字符替换成a

qDebug() << s;  // "alo"

 

trimmed() simplified() 移除字符串两端的空白字符

QString s = "   hello";
s = s.trimmed();

qDebug() << s;  // "hello"

 

 

 

四、判断

startsWith() 判断字符串是否以某个字符开头
endsWith() 判断字符串是否以某个字符结尾

QString s = "hello";

// true,大小写不敏感
qDebug() << s.startsWith("H", Qt::CaseInsensitive);

// true,大小写敏感
qDebug() << s.startsWith("h", Qt::CaseSensitive);

 

isNull() isEmpty() 字符串判空

qDebug() << QString().isNull();     // true
qDebug() << QString().isEmpty();    // true
qDebug() << QString("").isNull();   // false
qDebug() << QString("").isEmpty();  // true

 

 

 

五、字符串间比较

operator<(const QString&)  // 字符串小于另一个字符串,true
operator<=(const QString&) // 字符串小于等于另一个字符串,true
operator==(const QString&) // 两个字符串相等,true
operator>=(const QString&) // 字符串大于等于另一个字符串,true

// 比较两个字符串,返回数字
localeAwareCompare(const QString&, const QStriing&)

// 加入了大小写是否敏感参数,返回数字
compare(const QString&, const QString&, Qt::CaseSensitivity)

 

 

 

 

六、字符串格式转换

toInt()   // 转整形
toDouble()  // 转双进度浮点数
toFloat()   // 转单精度浮点数
toLong()    // 转长整型
toLongLong()  // 转长长整形

toAscii()  // 返回一个ASCII编码的8位字符串
toLatin1() // 返回一个Latin-1(ISO8859-1)编码的8位字符串
toUtf8()   // 返回一个UTF8编码的8位字符串
toLocal8Bit()   // 返回一个系统本地编码的8位字符串

 

 

 

 

 

posted @ 2021-09-01 23:22  十一的杂文录  阅读(934)  评论(0编辑  收藏  举报