【QT学习】| QString | 子串分隔问题

  • Qt中QString中提供两种简单易行的分隔字符串的函数,section和split

1.QString seciton

QString::section提供了四种重载函数,如下:

QStringsection(QChar sep, int start, int end = -1, SectionFlags flags = SectionDefault) const
QStringsection(const QString & sep, int start, int end = -1, SectionFlags flags = SectionDefault) const
QStringsection(const QRegExp & reg, int start, int end = -1, SectionFlags flags = SectionDefault) const
QStringsection(const QRegularExpression & re, int start, int end = -1, SectionFlags flags =
 QString test("one,two,three,four,five");
 test=test.section(',',2,2); // "three"
 test=test.section(',',-2,-2); //"four" 
 test=test.section(',',2); //"three,four,five" 

 QString:
 QString test("oneistwoisthree");
 test=test.section("is",1,1);//two

 QRegExp:
 QString test1("one,two*three/four/five^six");
 QString test2("one,two*three/four!five^six");
 
 QString test=test1.section(QRegExp(QString("[,*/^]")),1,3);//"test=two*three/four"
 test=test2..section(QRegExp(QString("[,*/^]")),1,3);//test="two*three/four!five"

不在正则表达式内所以无法分隔判断"four!five"被认为是3位置上的字符串

2.QString::split

  • QString 中提供关于split的函数如下:

QStringList split(const QString & sep, SplitBehavior behavior = KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
QStringList split(QChar sep, SplitBehavior behavior = KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
QStringList split(const QRegExp & rx, SplitBehavior behavior = KeepEmptyParts) const
QStringList split(const QRegularExpression & re, SplitBehavior behavior = KeepEmptyParts) const
split函数入口第一个参数也为分隔判定符,第二个参数为SplitBehavior,设置是否跳过空格符,默认是保留空格符。

QString test("one,two,three,,four,five");
QList lst;
lst=test.split(',');//lst={"one","two","three","","four","five"}
lst=test.split(',',QString::SkipEmptyParts);//lst={"one","two","three","four","five"}

QStringList lst;
QString test("one,two*three/four/five^six"); 
lst=test.split(QRegExp("[,*/^]"));//lst={"one","two","three","four","five","six"}

3.section和split的区别:

section只对字符串进行分隔判定,可判断后不同位置上的字符串,而split将整个字符串进行拆分,得到多个字符串,返回所有分隔出来的字符串到QStringList中,要想获得某个位置的字符串,需从QStringList中获取。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值