参考:http://zetcode.com/gui/qt5/strings/
由于我们不需要Qt GUI模块,但是GUI模块为默认加载的,所以我们需要在.pro
文件内加上QT -= gui
。
第一个示例
使用QString
类中的基础的类。
// basic.cpp
#include <QTextStream>
int main(void) {
QTextStream out(stdout);
QString a = "love"; //将字符串a的内容初始化为love;
//在下面的字符串操作中,改变的为字符串a本身;
a.append(" chess"); //在字符串a后面添加 chess;
a.prepend("I "); //在字符串a前面添加I ;
out << a << endl; //输出字符串a;
//输出字符串a的长度字符数;
out << "The a string has " << a.count()
<< " characters" << endl;
out << a.toUpper() << endl; //将字符串a的字母全部修改为大写字母后输出
out << a.toLower() << endl; //将字符串a的字母全部修改为小写字母后输出
out << a << endl; //输出字符串a
return 0;
}
在这个示例中,我们先初始化了一个QString
字符串,然后在字符串前面和后面增加了一些字符串,输出字符串长度,然后输出字符串的大写和小写字母。
//输出字符串a的长度字符数;
out << "The a string has " << a.count()
<< " characters" << endl;
count()
范围指定字符串中字符数量,该函数与size()
和length()
的效果是一样的。
out << a.toUpper() << endl; //将字符串a的字母全部修改为大写字母后输出
out << a.toLower() << endl; //将字符串a的字母全部修改为小写字母后输出
toUpper()
和toLower()
的作用分别是返回字符串的大写字母和小写字母。
函数的输出结果为:
$ ./basic
I love chess
The a string has 12 characters
I LOVE CHESS
i love chess
I love chess
字符串初始化
QString
具有多种初始化方法。
// init.cpp
#include <QTextStream>
int main(void) {
QTextStream out(stdout);
// 传统字符串初始化方法
QString str1 = "The night train";
out << str1 << endl;
// 初始化QString的对象方法
QString str2("A yellow rose");
out << str2 << endl;
// 通过C++标准库初始化
std::string s1 = "A blue sky";
QString str3 = s1.c_str();
out << str3 << endl;
// 将C++标准字符串转换为QString
std::string s2 = "A thick fog";
QString str4 = QString::fromLatin1(s2.data(), s2.size());
out << str4 << endl;
// C语言字符串
char s3[] = "A deep forest";
QString str5(s3);
out << str5 << endl;
return 0;
}
其中
// 通过C++标准库初始化
std::string s1 = "A blue sky";
QString str3 = s1.c_str();
使用c_str()
方法来生成一个以空字符结尾的字符序列。这个字符数组(一个字符串的经典c表示)可以被分配给一个QString
变量。
// 将C++标准字符串转换为QString
std::string s2 = "A thick fog";
QString str4 = QString::fromLatin1(s2.data(), s2.size());
我们使用fromlatin1()
方法。它需要一个指向字符数组的指针。指针返回std :: string
的data()
方法。第二个参数是std :: string
的大小。
函数的输出结果为:
$ ./init
The night train
A yellow rose
A blue sky
A thick fog
A deep forest
获取字符串元素
QString
是QChars
序列。字符串元素可以用过[]
操作符或者at()
方法获得。
// access.cpp
#include <QTextStream>
int main(void) {
QTextStream out(stdout);
QString a = "Eagle";
// 输出字符串第一个和第五个元素
out << a[0] << endl;
out << a[4] << endl;
// 输出字符串第一个元素
out << a.at(0) << endl;
// 判断获取字符串元素是否超过字符串范围
if (a.at(5).isNull()) {
out << "Outside the range of the string" << endl;
}
return 0;
}
其中:
// 输出字符串第一个元素
out << a.at(0) << endl;
// 判断获取字符串元素是否超过字符串范围
if (a.at(5).isNull()) {
out << "Outside the range of the string" << endl;
}
at()
方法返回字符串的元素,如果超出字符串长度,则返回NULL
。
输出结果为:
$ ./access
E
e
E
Outside the range of the string