Qt QString: Summary of common member functions

QString is one of the most frequently used data types in Qt, mainly because it provides a large number of powerful member functions. Here are some commonly used member functions:

1. String processing related

1.1 split() (split string)

The split() function can split a string into a QStringList with multiple substrings. Examples are as follows:

QString str = "polluter pays principle";
//根据空格拆分字符串
QStringList words = str.split(" ");
qDebug() << words; //returns ("polluter", "pays", "principle")

In the example above, we split "polluter pays principle" into three substrings: "polluter", "pays" and "principle".

1.2 section() (split string)

The section() function is used to split a string by a certain character. The function prototype is:

QString QString::section (QChar sep, int start, int end = -1, SectionFlags flags = SectionDefault) const

This function regards the string as several blocks, these blocks are separated by sep, start and end specify the block number, end defaults to -1, and returns a string composed of blocks in [ start, end ].

The function of the following example: Get the second substring separated by ',' from the string "one, two, three, four", namely "two".

QString str = "one, two, three, four";
cout << str.section(',', 1, 1).trimmed().toStdString() << endl; //returns two

The result is "two", with no leading or trailing spaces. The above function trimmed() is to remove the ASCII characters '\t', '\n', '\v', '\f', '\r' and ' ' before and after the string.

Look at another example, this example is to get the second substring separated by ',' and '^' from the string "one, two* three / four / five ^ six", namely "four";

QString str = "one, two* three / four / five ^ six";
cout << str.section(QRegExp("[,*/^]"), 3, 3).trimmed().toStdString() << endl;

A simple regular expression is used above, which can be constructed by class QRegExp in Qt, and the function section() supports the use of regular expressions.

1.3 mid() (intercept substring)

mid() intercepts the substring, that is, returns the substring from the given position (parameter 1) to the given length (parameter 2). If there is no parameter 2, it will return the substring from the starting point to the end of the string. Examples are as follows:

QString x = "Nine pineapples";
QString y = x.mid(5, 4);            // y == "pine"
QString z = x.mid(5);               // z == "pineapples"

There are also left() and right() similarly, which respectively return n characters from the left (left interception) and n characters from the right (right interception). In contrast, mid() can intercept substrings from any starting point , which is more powerful and more general.

1.4 replace() (replace substring)

replace() can replace some substrings in the source string. The most commonly used function prototype is:

QString &QString::replace(int position, int n, const QString &after)

Parameter 1 is the starting replacement position, parameter 2 is the length of the new substring, and parameter 3 is the new substring. Examples are as follows:

QString x = "Say yes!";
QString y = "no";
x.replace(4, 3, y); // x == "Say no!"

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓ 

2. Type conversion related

QString provides a large number of member functions for type conversion, so it is often used as an intermediary type in projects.

2.1 QString to char*

Examples are as follows:

char *charP;
QString str = "hello";
charP = str.toLatin1().data();

Among them, after converting toLatin1() to QByteArray type, use data() to convert the string of QByteArray type to char* type.

2.2 char* to QString

Examples are as follows:

char *charP = "hello";
QString str = QString(charP);

2.3 QString to int/double and other numerical types

The prototype of the toInt() function is as follows:

int toInt(bool *ok=0, int base=10) const;

Parameter 1 ok indicates whether the conversion is successful, if successful, ok is true, and if it fails, ok is false. Parameter 2 base indicates the conversion base, and the default is base 10. If it is the default base 10, and the string is not a pure number, the final conversion result of int is 0. The same is true for hexadecimal.

Examples are as follows:

QString str1 = "FF";
QString str2 = "23";
QString str3 = "12.3";
bool ok = false;

int hex = str1.toInt(&ok,16); // hex == 255, ok == true
int dec = str2.toInt(); // dec == 23, ok == true
float fNum = str3.toFloat(); // fNum == 12.3, ok == true

2.4 Convert numeric types such as int/double to QString

Int/double type conversion QString type, use QString::number() function;

The first parameter is: int/double data to be converted; the second parameter is: base. 10, 2, 8, etc.; the third parameter is: precision;

int num = 15;
double doubleVal = 15.23;
QString strDec = QString::number(num); // strDec == "15"
QString strHex = QString::number(num,16).toUpper(); // strHex == "F"
QString strDouble = QString::number(doubleVal, 10, 2); // strDouble == "15.23"

toUpper() can convert lowercase letters to uppercase letters. You can also use the setNum() function, examples are as follows:

QString str1,str2;
str1.setNum(20);
str2.setNum(12.3);

qDebug() << str1; //returns "20"
qDebug() << str2; //returns "12.3"

3. Build string related

3.1 sprintf()

A completely different way of combining strings, for example:

str.sprintf("%s %.1f%%", "perfect competition", 100.0);

Supports the same format specifiers as the C++ library's sprintf() function. In the above example, str is assigned the value "perfect competition 100.0%".

3.2 arg()

Another way to build a string from another string or number, examples are as follows:

QString str = QString("%1:%2 %3:%4").arg("time").arg("2019-5-30").arg("value").arg(25.8); //returns "time:2019-5-30 value:25.8"

In this example, "%1" is replaced by "time", "%2 is replaced by "2019-5-30", "%3" is replaced by "value", and "%4" is replaced by 25.8. The result is" time:2019-5-30 value:25.8".
In general, arg() is a better solution than sprintf() because it is type-safe, fully supports Unicode, and supports various Such data type.

4. Query string correlation

4.1 isEmpty()

isEmpty() Determines whether the string is empty, and returns true if it is, otherwise returns false. Examples are as follows:

qDebug() << QString().isEmpty(); //returns true
qDebug() << QString("").isEmpty(); //returns true
qDebug() << QString(" ").isEmpty(); //returns false (空格也是字符)
qDebug() << QString("a").isEmpty(); //returns false

4.2 contains()

contains() Determines whether there is a substring in the string, and returns true if there is, otherwise returns false. Examples are as follows:

QString str = "winter is coming";
qDebug() << str.contains("coming"); //returns true
qDebug() << str.contains("bad"); //returns false

4.3 indexOf()

indexOf() Query whether a specific substring is contained, return the starting position, and return -1 to indicate not found. Parameter 1 is the substring of the query, and parameter 2 indicates the starting point of the query. The example is as follows

QString x = "sticky question";
QString y = "sti";
x.indexOf(y);               // returns 0
x.indexOf(y, 1);            // returns 10
x.indexOf(y, 10);           // returns 10
x.indexOf(y, 11);           // returns -1

The third parameter Qt::CaseSensitivity can be case-sensitive. Generally, the default value Qt::CaseSensitive is used to indicate that case-sensitivity is enabled.

4.4 startsWith() 和 endsWith()

To check if a string starts or ends with something, we can use the startsWith() and endsWith() functions. Examples are as follows:

if (url.startsWith("http:") && url.endsWith(".png"))

This is simpler and faster than:

if (url.left(5) == "http:" && url.right(4) == ".png")

Five, filter string related

5.1 trimmed()

If you need to filter out the whitespace characters at both ends of the string ('\t', '\v', '\f', '\r', '\n', and ' '), you can use the trimmed() function. Examples are as follows:

QString str = " time is good\t";
qDebug() << str.trimmed(); //returns "time is good"

5.2 simplified()

If you not only need to filter out the whitespace characters at both ends, but also want to replace one or more internal whitespace characters with a single space, then you need to use the simplified() function. Examples are as follows:

QString str = "  time\t\n   is\n   good\t";
qDebug() << str.simplified(); //returns "time is good"

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

Guess you like

Origin blog.csdn.net/QtCompany/article/details/131730864