QString简单测试

QString的简单测试程序:

#include <QCoreApplication>
#include <QDebug>
#include <QStringList>
#include <QTextCodec>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QTextCodec::setCodecForTr(QTextCodec::codecForName("Utf-8"));

    qDebug()<<QObject::tr("以下是编辑字符串操作:")<<endl;
    QString str = "hello!";
    qDebug()<<QObject::tr("字符串大小:")<<str.size();
    str[0] = QChar('H');
    qDebug()<<QObject::tr("第一个字符:")<<str[0];
    str.append(" Qt");
    str.replace(1,4,'i');
    str.insert(2,"my");
    qDebug()<<QObject::tr("str为: ")<<str;
    str = str +"!!!";
    qDebug()<<QObject::tr("str为: ")<<str;
    str = "hi\r\n Qt!\n";
    qDebug()<<QObject::tr("str为: ")<<str;
    QString str1 = str.trimmed();
    qDebug()<<QObject::tr("str1为: ")<<str1;
    QString str2 = str.simplified();
    qDebug()<<QObject::tr("str2为: ")<<str2;

    str = "Hi,my,,Qt!";
    QStringList list = str.split(",",QString::SkipEmptyParts);
    qDebug()<<QObject::tr("str拆分后为: ")<<list;
    str = list.join(" ");
    qDebug()<<QObject::tr("list组合后为: ")<<str;
    qDebug()<<QString().isNull();       //返回值为:true
    qDebug()<<QString().isEmpty();      //返回值为:true
    qDebug()<<QString("").isNull();     //返回值为:false
    qDebug()<<QString("").isEmpty();    //返回值为:true

    return a.exec();
}

输出为:
这里写图片描述

QT中,判断一个QString中是否包含中文也可以通过遍历字符串的每个字符,然后判断该字符的Unicode编码是否在中文的Unicode编码范围内来实现。与C++字符串不同的是,QT中的QString默认以UTF-16编码存储,因此需要将其转换为UTF-8编码后再进行判断。以下是一个简单的示例代码: ```c++ #include <iostream> #include <QString> #include <QTextCodec> bool hasChinese(const QString& str) { QTextCodec* codec = QTextCodec::codecForName("UTF-8"); QByteArray encodedStr = codec->fromUnicode(str); for(int i = 0; i < encodedStr.size(); i += 3) { unsigned int code = (encodedStr[i] & 0xff) << 16 | (encodedStr[i + 1] & 0xff) << 8 | (encodedStr[i + 2] & 0xff); if(code >= 0x4E00 && code <= 0x9FA5) { return true; } } return false; } int main() { QString str1 = "hello world"; QString str2 = "你好,世界"; std::cout << hasChinese(str1) << std::endl; // 输出0 std::cout << hasChinese(str2) << std::endl; // 输出1 return 0; } ``` 在这个示例代码中,我们定义了一个名为`hasChinese`的函数,它接受一个QString参数,然后将其转换为UTF-8编码的字节数组。接下来,我们遍历字节数组中的每个字符,将每三个字节组合成一个Unicode编码,然后判断该编码是否在中文的范围内。最后,如果整个字符串中没有中文就返回`false`。在`main`函数中,我们分别测试了一个只包含英文字母和一个包含中文的字符串,结果都是符合预期的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值