参考:http://zetcode.com/gui/qt5/strings/
循环遍历字符串
QString
又QChars
组成。可以通过循环访问QString
来访问字符串的每个元素。
// looping.cpp
#include <QTextStream>
int main(void) {
QTextStream out(stdout);
QString str = "There are many stars.";
//在输出的每个字母之间加入一个空格
foreach (QChar qc, str) {
out << qc << " ";
}
out << endl;
//使用迭代器遍历
for (QChar *it=str.begin(); it!=str.end(); ++it) {
out << *it << " " ;
}
out << endl;
//计算字符串的大小并使用at()方法来访问字符串元素。
for (int i = 0; i < str.size(); ++i) {
out << str.at(i) << " ";
}
out << endl;
return 0;
}
上述代码提供了三种方式遍历字符串。
foreach
是Qt对C++语言的一个扩展,关键字的第一个参数是字符串元素,第二个参数是字符串。
输出结果:
$ ./looping
T h e r e a r e m a n y s t a r s .
T h e r e a r e m a n y s t a r s .
T h e r e a r e m a n y s t a r s .
字符串比较
QString :: compare()
静态方法用于比较两个字符串。该方法返回一个整数。如果返回值小于零,则第一个字符串小于第二个字符串。如果它返回零,两个字符串都是相等的。最后,如果返回值大于零,则第一个字符串大于第二个字符串。’less’表示字符串中的特定字符位于字符表中的另一个字符之前。字符串按以下方式比较:两个字符串的第一个字符进行比较;如果它们相等,则比较以下两个字符,直到找到一些不同的字符或者我们发现所有字符匹配。
// comparing.cpp
#include <QTextStream>
#define STR_EQUAL 0
int main(void) {
QTextStream out(stdout);
QString a = "Rain";
QString b = "rain";
QString c = "rain\n";
// 比较字符串a,b,第一个字符不同
if (QString::compare(a, b) == STR_EQUAL) {
out << "a, b are equal" << endl;
} else {
out << "a, b are not equal" << endl;
}
out << "In case insensitive comparison:" << endl;
// 在大小写不敏感的情况下对a、b进行比较
if (QString::compare(a, b, Qt::CaseInsensitive) == STR_EQUAL) {
out << "a, b are equal" << endl;
} else {
out << "a, b are not equal" << endl;
}
if (QString::compare(b, c) == STR_EQUAL) {
out << "b, c are equal" << endl;
} else {
out << "b, c are not equal" << endl;
}
//删除c字符串的最后一个元素
c.chop(1);
out << "After removing the new line character" << endl;
if (QString::compare(b, c) == STR_EQUAL) {
out << "b, c are equal" << endl;
} else {
out << "b, c are not equal" << endl;
}
return 0;
}
使用compare()
进行区分大小写和不区分大小写的比较。
if (QString::compare(a, b, Qt::CaseInsensitive) == STR_EQUAL) {
out << "a, b are equal" << endl;
} else {
out << "a, b are not equal" << endl;
}
Qt::CaseInsensitive
:对字符串进行比较,并且忽略大小写
c.chop(1);
chop()
:移除字符串的最后元素
输出结果
$ ./comparing
a, b are not equal
In case insensitive comparison:
a, b are equal
b, c are not equal
After removing the new line character
b, c are equal
字符串转换
字符串通常需要转换为其他数据类型,反之亦然。toInt()
,toFloat()
,toLong()
是将字符串转换为整数、浮点数和长整数的三种QString
方法。setNum()
方法将各种数字数据类型转换为字符串。该方法被重载并且自动调用正确的方法。
// converting.cpp
#include <QTextStream>
int main(void) {
QTextStream out(stdout);
QString s1 = "12";
QString s2 = "15";
QString s3, s4;
out << s1.toInt() + s2.toInt() << endl;
int n1 = 30;
int n2 = 40;
out << s3.setNum(n1) + s4.setNum(n2) << endl;
return 0;
}
在这个例子中,将两个字符串转换为整数并计算他们的和。然后将两个整数转换为字符串并连接它们。
out << s1.toInt() + s2.toInt() << endl;
toInt()
方法经字符串转换为数字。
out << s3.setNum(n1) + s4.setNum(n2) << endl;
setNum()
将整数转换成字符串。
输出结果:
$ ./converts
27
3040