QString的常用功能

本文最后更新于:2022年5月23日 晚上

append() 和 prepend()

1
2
3
4
QString str1 = "卖", str2 = "拐";
QString str3 = str1;
str1.append(str2); // str1 = "卖拐"
str3.prepend(str2); // str3 = "拐卖"

toUpper() 和 toLower()

1
2
3
QString str1 = "Hello, World", str2;
str2 = str1.toUpper(); // str2 = "HELLO, WORLD"
str2 = str1.toLower(); // str2 = "hello, world"

count()、size() 和 length()

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

trimmed() 和 simplified()

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

indexOf() 和 lastIndexOf()

1
2
3
4
5
// int indexOf(const QString& str, int form = 0, Qt::CaseSensitivity cs =
// Qt::CaseSensitive) const
QString str1 = "G:\Qt6Book\QT6.3Study\qw.cpp";
N = str1.indexOf("6.3"); // N = 13
N = str1.lastIndexOf("\\"); // N = 21 '//'第一个/表示转换符

isNull() 和 isEmpty()

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

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


contais()

1
2
3
4
5
6
QString str1 = "G:\Qt6Book\QT6.3Study\qw.cpp";
N = str1.contains(".cpp", Qt::CaseInsensitive);
// N = true, 不区分大小写

N = str1.contains(".CPP", Qt::CaseSensitive);
// N = false, 区分大小写

endsWith() 和 startsWith()

1
2
3
4
5
6
QString str2, str1 = "学生姓名,男,1984-3-4,汉族,山东";
N = str1.indexOf(","); // N = 4, 第一个","出现的位置
str2 = str1.left(N); // str2 = "学生姓名"
N = str1.lastIndexOf(","); // N = 18, 最后一个逗号的位置
str2 = str1.right(str1.size() - N - 1);
// str2 = "山东", 提取最后一个逗号之后的字符串

section()

1
2
3
4
5
6
7
8
9
// QString section(const QString& sep, int start, int end = -1,
// SectionFlags flags = SectionDefault) const

QString str2, str1 = "学生姓名,男,1084-3-4,汉族,山东";
str2 = str1.section(",", 0, 0);
// str2 = "学生姓名", 第1段的编号为0
str2 = str1.section(",", 1, 1); // str2 = "男"
str2 = str1.section(",", 0, 1); // str2 = "学生姓名,男"
str2 = str1.section(",", 4, 4); // str2 = "山东"

QString的常用功能
https://tian-sj.github.io/2022/05/10/QString的常用功能/
作者
田世纪
发布于
2022年5月10日
许可协议