QString QString::section(QChar(qchar.html) sep, int start, int end = ..., QString::SectionFlags(qstring.html#SectionFlag-enum) flags = SectionDefault) const
This function returns a section of the string.
This string is treated as a sequence of fields separated by the character, sep. The returned string consists of the fields from position start to position end inclusive. If end is not specified, all fields from position start to the end of the string are included. Fields are numbered 0, 1, 2, etc., counting from the left, and -1, -2, etc., counting from right to left.
The flags argument can be used to affect some aspects of the function's behavior, e.g. whether to be case sensitive, whether to skip empty fields and how to deal with leading and trailing separators; see SectionFlags(qstring.html#SectionFlag-enum).
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"
QStringList QString::split(const QString &sep, QString::SplitBehavior behavior = KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
Splits the string into substrings wherever sep occurs, and returns the list of those strings. If sep does not match anywhere in the string, split() returns a single-element list containing this string.
cs specifies whether sep should be matched case sensitively or case insensitively.
If behavior is QString::SkipEmptyParts, empty entries don't appear in the result. By default, empty entries are kept.
Example:
QString str = "a,,b,c";
QStringList list1 = str.split(',');
// list1: "a", "", "b", "c"
QStringList list2 = str.split(',', QString::SkipEmptyParts);
// list2: "a", "b", "c"
If sep is empty, split() returns an empty string, followed by each of the string's characters, followed by another empty string:
QString str = "abc";
auto parts = str.split("");
// parts: {"", "a", "b", "c", ""}
To understand this behavior, recall that the empty string matches everywhere, so the above is qualitatively the same as:
QString str = "/a/b/c/";
auto parts = str.split('/');
// parts: {"", "a", "b", "c", ""}
网友评论