QString 子串分隔

Qt中QString中提供两种简单易行的分隔字符串的函数,section和split
1.QString seciton
QString::section提供了四种重载函数,如下:
QString section(QChar sep, int start, int end = -1, SectionFlags flags = SectionDefault) const
QString section(const QString & sep, int start, int end = -1, SectionFlags flags = SectionDefault) const
QString section(const QRegExp & reg, int start, int end = -1, SectionFlags flags = SectionDefault) const
QString section(const QRegularExpression & re, int start, int end = -1, SectionFlags flags = SectionDefault) const
section入口的第一个参数为分隔判定符(字符,字符串,正则表达式),start为起始位置,end为结束位置,最后一个为sectionFlag.开始和结束位置不是附属,从左边开始计数,为0,1,2···,如果是负数就从右边开始计数,为-1,-2,···,end没有设置时,默认到字符串结束位置。
Qchar:
 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"}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值