1 分割字符串
1)section方式
1.1)单个字符分割
QString QString::section(QChar sep, int start, int end = -1, SectionFlags flags = SectionDefault) const
QString str;
QString csv = "forename,middlename,surname,phone";
QString path = "/usr/local/bin/myapp"; // First field is empty
QString::SectionFlag flag = QString::SectionSkipEmpty;
str = csv.section(',', 2, 2); // str == "surname"
str = path.section('/', 3, 4); // str == "bin/myapp"
str = path.section('/', 3, 3, flag); // str == "myapp"
If start or end is negative, we count fields from the right of the string, the right-most field being -1, the one from right-most field being -2, and so on.
str = csv.section(',', -3, -2); // str == "middlename,surname"
str = path.section('/', -1); // str == "myapp"
1.2)字符串分割
QString QString::section(const QString &sep, int start, int end = -1, SectionFlags flags = SectionDefault) const
QString str;
QString data = "forename**middlename**surname**phone";
str = data.section("**", 2, 2); // str == "surname"
str = data.section("**", -3, -2); // str == "middlename**surname"
1.3)正则分割
QString QString::section(const QRegExp ®, int start, int end = -1, SectionFlags flags = SectionDefault) const
This function overloads section().
This string is treated as a sequence of fields separated by the regular expression, reg.
QString line = "forename\tmiddlename surname \t \t phone";
QRegExp sep("\\s+");
str = line.section(sep, 2, 2); // str == "surname"
str = line.section(sep, -3, -2); // str == "middlename surname"
2)split方式
2.1)
QStringList QString::split(const QString &sep, SplitBehavior behavior = KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
QString str = "a,,b,c";
QStringList list1 = str.split(',');
// list1: [ "a", "", "b", "c" ]
QStringList list2 = str.split(',', QString::SkipEmptyParts);
// list2: [ "a", "b", "c" ]
2.2)正则
QStringList QString::split(const QRegExp &rx, SplitBehavior behavior = KeepEmptyParts) const
Here's an example where we extract the words in a sentence using one or more whitespace characters as the separator:
QString str;
QStringList list;
str = "Some text\n\twith strange whitespace.";
list = str.split(QRegExp("\\s+"));
// list: [ "Some", "text", "with", "strange", "whitespace." ]
Here's a similar example, but this time we use any sequence of non-word characters as the separator:
str = "This time, a normal English sentence.";
list = str.split(QRegExp("\\W+"), QString::SkipEmptyParts);
// list: [ "This", "time", "a", "normal", "English", "sentence" ]
Here's a third example where we use a zero-length assertion, \b (word boundary), to split the string into an alternating sequence of non-word and word tokens
str = "Now: this sentence fragment.";
list = str.split(QRegExp("\\b"));
// list: [ "", "Now", ": ", "this", " ", "sentence", " ", "fragment", "." ]
翻译自QT手册
来源:CSDN
作者:清水迎朝阳
链接:https://blog.csdn.net/shuilan0066/article/details/104777813