QT 学习(九) -- QT中的字符串类

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();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值