Qt 字符串截取分割

本文主要是讲QString的分割 

这里,主要讲几个拆分字符的用法:

实例一,indexOf,mid,left,remove的用法:

#include <QCoreApplication>
#include <QString>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QString str_source = "asda;weqw;123213;12312;asdsa";
    str_source = str_source.trimmed();// 移除str_source字符串两端的空白字符
    str_source += QString(";");
    qDebug() << str_source;
    while(str_source != "")
    {
        int nIndex = str_source.indexOf(";");
        qDebug() << nIndex;// 由打印结果可以得到 nIndex 表示的是第一个分号之前的
//        QString str_target = str_source.left(nIndex);// 这儿是取前nIndex位
        QString str_target = str_source.mid(0,nIndex);// 从0开始取nIndex个
        qDebug() << str_target;// 有结果可知 asda weqw 123213 12312 asdsa
        str_source = str_source.remove(0,nIndex+1); // 把分号也去掉
    }

    return a.exec();
}

实例二:startsWith,trimmed,remove,indexOf,mid

#include <QCoreApplication>
#include <QString>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QString str_source = "#asda#weqw#123213#12312#asdsa";
    str_source = str_source.trimmed();// 移除str_source字符串两端的空白字符
    str_source += QString("#"); // 便于一起操作
    qDebug() << str_source;
    if(str_source.startsWith("#"))
    {
        while(str_source.startsWith("#"))
        {
            str_source.remove(0,1);
            if(str_source == NULL) // 有可能出现两个##相连的问题 和 结尾的#
            {
                continue;
            }
            int nIndex = str_source.indexOf("#"); // 到下一次出现时
            QString str_target = str_source.mid(0,nIndex);// 从0开始取nIndex个
            qDebug() << str_target;
            str_source = str_source.remove(0,nIndex); // 把分号也去掉
        }
    }

    return a.exec();
}

主要是防止自己什么时候忘了,记录一下用法。

欢迎大家加我的群:460952208

  • 1
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值