Qt learning path (50): QString

Source: Internet
Author: User

This time I went home and had no time to write it. Today I found that my blog editor has a new version. Let's try the new editor function first!

Today we are talking about QString. The reason why QString is taken out separately is that string is a very common data structure, even in many languages, such as JavaScript, string is implemented as a basic data structure similar to int.

Every GUI program requires a string. These strings can be used as prompts on the interface or as common data structures. The C ++ language provides two string implementations: a c-style string ending with '\ 0'; std: string, that is, the class in the standard template library. Qt provides its own string implementation: QString. QString is encoded with 16-bit Uniode. We usually use ASCII and other character sets as a subset of Unicode encoding. We will explain the encoding in detail later.

When using QString, we do not need to worry about memory allocation and the considerations for ending with '\ 0. QString solves these problems. Generally, you can regard QString as a vector of QChar. In addition, unlike a C-style string, QString can contain the '\ 0' symbol in the middle, while the length () function returns the length of the entire string, it is not just the length from the start to '\ 0.

Similar to Java's String class, QString also loads the ++ and ++ = operators. These two operators can connect two strings, just like the operations in Java. QString can automatically expand the memory usage, which is a fast connection operation. The use of these two operators is as follows:

 
 
  1. QString str = "User: ";  
  2. str += userName + "\n"; 

The append () function of QString provides similar operations, such:

 
 
  1. str = "User: ";  
  2. str.append(userName);  
  3. str.append("\n"); 

The C language contains the printf () function as the formatting output, and QString provides a sprintf () function to implement the same function:

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

This code will output: perfect competition 100.0%, the same as printf () in C language. However, we have also seen another function arg () provided by Qt To Format String output ():

 
 
  1. str = QString("%1 %2 (%3s-%4s)")  
  2.       .arg("permissive").arg("society").arg(1950).arg(1970); 

In this Code, % 1, % 2, % 3, % 4 are used as placeholders and will be replaced by the content in the later arg () function. For example, % 1 will be replaced with permissive, % 2 will be replaced with society, % 3 will be replaced with 1950, % 4 will be replaced with Zeng 1970, and finally, the output of this Code is: permissive society (1950 s-1970 s ). the arg () function is type-safe than sprintf () and accepts multiple data types as parameters. Therefore, we recommend that you use the arg () function instead of the traditional sprintf () function ().

You can use the static function number () to convert a number to a string. For example:

 
 
  1. QString str = QString::number(54.3); 

You can also use the non-static function setNum () to achieve the same purpose:

 
 
  1. QString str;  
  2. str.setNum(54.3); 

A series of to functions can convert strings to other basic types, such as toInt (), toDouble (), and toLong. These functions all accept a bool pointer as a parameter. After the function is completed, it is set to true or false based on whether the conversion is successful:

 
 
  1. bool ok;  
  2. double d = str.toDouble(&ok);  
  3. if(ok)  
  4. {  
  5.     // do something...  
  6. } else {  
  7.     // do something...  

For QString, Qt provides many operation functions. For example, you can use the mid () function to intercept substrings:

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

The mid () function accepts two parameters: the first is the starting position and the second is the length of the string. If the second parameter is omitted, It is truncated from the starting position to the end. As shown in the preceding example.

The left () and rigt () functions are similar to each other. They both accept an int-type parameter n, which is used to intercept strings. The difference is that the left () function intercepts n characters from the left side, while right () truncates from the right side. The following is an example of left:

 
 
  1. QString x = "Pineapple";  
  2. QString y = x.left(4);      // y == "Pine" 

The indexOf () function returns the position of the string, for example:

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

The startsWith () and endsWith () functions can detect whether a string starts or ends with a specific string. For example:

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

This code is equivalent

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

However, the former is clearer and more concise than the latter, and the performance is faster.

QString also provides the replace () function to replace strings. The trimmed () function removes spaces on both sides of the string. (Note that blank spaces include spaces, tabs, and line breaks, the toLower () and toUpper () functions convert strings into lowercase uppercase strings. The remove () and insert () functions provide the ability to delete and insert strings; the simplified () function can replace all consecutive white spaces in the string with one and remove the white spaces at both ends. For example, "\ t" returns a space "".

It is also common to convert a const char * type C-style string to a QString. To put it simply, the QString + = function can be completed:

 
 
  1. str += " (1870)"; 

Here, we convert the const char * type string "(1870)" to the QString type. If Explicit conversions are required, you can use the forced conversion operation of QString or the fromAscii () function. To convert the QString type into a const char * string, you need to perform two steps. One is to use toAscii () to obtain a QByteArray type object, and then call its data () or constData () function, for example:

 
 
  1. printf("User: %s\n", str.toAscii().data()); 

For ease of use, Qt provides a macro qPrintable (), which is equivalent to toAscii (). constData (), for example:

 
 
  1. printf("User: %s\n", qPrintable(str)); 

We call the data () or constData () function in the QByteArray class to obtain a const char * string in QByteArray. Therefore, we do not need to worry about memory leakage or other issues, qt manages the memory for us. However, this also implies that we should not use this pointer for too long, because if QByteArray is deleted, this pointer will become a wild pointer. If the QByteArray object is not put in a variable, the QbyteArray object will be deleted after the statement ends, and the pointer will be deleted.

This article is from the "bean space" blog, please be sure to keep this source http://devbean.blog.51cto.com/448512/275360

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.