字符串比较
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;
}
循环遍历字符串
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;
}