QString和QStringList
QString
//QString定义 QString s1 = "abc"; QString s2("hello"); //字符串连接 QString s = s1 + s2; //组包 s = QString("a = %1, b = %2, c = %3").arg(250).arg("hello").arg(22.22); qDebug()<<s; //输出结果:a = 250, b = hello, c = 22.22 s = "a=250,b=hello,c=22.22"; //参数表示按逗号分隔, 拆分出第0段到第1段, 保存到tmp QString tmp = s.section(",", 0, 1); qDebug()<<"tmp = "<<tmp; //输出结果:tmp="a=250" tmp = tmp.section("=", 1, 1); qDebug()<<"tmp="<<tmp; //输出结果:tmp="250"; //QString转int int a = tmp.toInt(); qDebug()<<"a="<<a; //输出结果:a=250; //int转QString组包方式转 tmp = QString("%1").arg(123); qDebug()<<"tmp="<<tmp; //输出结果:tmp="123" //int转QString函数方式转 tmp = QString::number(234); //char *转QString const char * buf = "hello, world"; QString ss = buf; qDebug()<<"ss = "<< ss; //std::string转QString string s = "hello, world" QString ss = QString::fromStdString(s); qDebug()<<"ss = "<< ss; //std::wstring转QString std::wstring wstr(L"你好, 世界"); QString ss = QString::fromStdWString(wstr); qDebug()<<"ss = "<< ss; //字符数组转QString char buf2[100] = "hello world"; ss = buf2; qDebug()<<"ss = "<<ss; //QString转char * ss = "hello abc"; //如果没有中文: QByteArray tmp = ss.toLatin1(); char * buf3 = tmp.data(); //如果有中文: QByteArray tmp = ss.toLocal8Bit(); char * buf4 = tmp.data(); //替换QString中字符串 QString text("text-decoration: none"); text.replace("none", "underline"); //去除QString首尾的空格(包括'\t', '\n', '\v', '\f', '\r') QString text(" text-decoration: none "); text = text.trimmed(); //字符移除操作 QString test = "hello,china"; QString tmp = test.remove(2, 4); //从下标2的字符开始, 移除4个字符 qDebug() << "test = " << test; //输出hechina qDebug() << "tmp = " << tmp; //输出hechina //判断字符是否以某字符或字符串开始 QString test= "@192.168.0.1"; if(true == test.startsWith("@")) { //do something } //判断QString是否空 QString().isEmpty(); // return true QString("").isEmpty(); // return true QString(" ").isEmpty(); // return false QString("abc").isEmpty(); // return false QString().isNull(); // return true QString("").isNull(); // return false QString(" ").isNull(); // return false QString("abc").isNull(); // return false
QStringList
//定义 QStringList list; //添加字符串 list << "hello"; list << "world"; list.append("abc"); //例子2 QStringList chinaMonth; chinaMonth << QStringLiteral("正月") << QStringLiteral("二月") << QStringLiteral("三月") << QStringLiteral("四月") << QStringLiteral("五月") << QStringLiteral("六月") << QStringLiteral("七月") << QStringLiteral("八月") << QStringLiteral("九月") << QStringLiteral("十月") << QStringLiteral("冬月") << QStringLiteral("腊月") ; //打印 qDebug()<< "list ="<< list; //遍历 for(int i = 0; i< list.size();++i) { QString tmp = list.at(i); qDebug()<<"tmp ="<< tmp; } //使用QStringList拆分QString QString str = "hello,world,abc,qt"; QStringList list2 = str.split(","); qDebug()<<"list2="<<list2; //输出:list2=("hello","world","abc","qt"); //判断QStringList中是否包含某个成员 bool b = list2.contains("123"); //移除QStringList中的成员 list2.removeOne("abc");