Qt字符串类的特点:
- 采用Unicode编码
- 采用隐式共享技术来节省内存和不必要的数据拷贝
- 跨平台使用,不必考虑字符串的平台兼容性
QString 与 string比较
QString支持字符串和数字的相互转换
支持字符串的大小比较
支持不同字符编码间的相互转换
支持std::string和std::wstring的相互转换
支持正则表达式的应用
示例代码:
#include <QtWidgets/QApplication>
#include <Qdebug.h>
#include <QString>
#include <QWidget>
void example_1()
{
QString s = "add";
s.append(" "); //字符串后添加空格 "add "
s.append("Qt"); //字符串后添加Qt "add Qt"
s.prepend(" "); //字符串前加空格 " add Qt"
s.prepend("C++");//在字符串加C++ "C++ add Qt"
qDebug() << s;
s.replace("add", "$"); //替换 "C++ $ Qt"
qDebug() << s;
}
void example_2()
{
QString a = " ";
int index = 0;
a.sprintf("%d. I'm %s, thank you!", 1, "tiancai"); //"1. I'm tiancai, thank you!"
qDebug() << a;
index = a.indexOf(","); //返回字符串a中逗号的下标
a = a.mid(0, index); //取子串。从第一个字符开始一直到之前定位的那个下标结束的这段字符
qDebug() << a; //"1. I'm tiancai"
index = a.indexOf(".");//定位到"."的下标
a = a.mid(index + 1, a.length()); //提取从"."的下一位开始到最后的字符串" I'm tiancai"
a = a.trimmed(); //去掉字符串中的空格
qDebug() << a; // "I'm tiancai"
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget w;
qDebug() << "example_1:";
example_1();
qDebug() << endl;
qDebug() << "example_2:";
example_2();
qDebug() << endl;
w.show();
return a.exec();
}
完善计算器中的字符串操作:
void QCalculatorUI::onButtonClicked()
{
//sender返回信号发送者的指针
QPushButton* btn = (QPushButton*)sender();
//存储当前按键的文本内容
QString clickText = btn->text();
if (clickText == "<-") {
//获得文本框中的text
QString Line_text = m_edit->text();
if (Line_text.length() > 0) {
Line_text.remove(Line_text.length()-1,1);
//删除之后重新显示
m_edit->setText(Line_text);
}
} else if (clickText == "C") {
m_edit->setText("");
} else if (clickText == "=") {
} else {
m_edit->setText(m_edit->text() + clickText);
}
qDebug() << "onButtonClicked()...";
qDebug() << btn->text();
}