Detailed explanation of strings in Qt5

Table of contents

  • Qt5 string basic example
  • Qt5 initialization string
  • Qt5 access to string elements
  • Qt5 string length
  • Qt5 build string
  • Qt5 substring
  • Qt5 looping through a string
  • Qt5 string comparison
  • Qt5 conversion string
  • letter
  • Qt5 modify string
  • Qt5 align string
  • Qt5 escape character

In this chapter, we use strings. Qt5 has a QString class for working with strings. It's very powerful and has many methods.

The QString class provides a Unicode string. It stores strings as 16-bit QChars. Each QChar corresponds to a Unicode 4.0 character. Unlike strings in many other programming languages, QStrings can be modified.

In the examples in this chapter, we don't need the Qt GUI module; we create command-line programs. Since the Qt GUI is included by default, we can disable it by adding the QT -= gui declaration in the project file.

The benefits of this article, free to receive Qt development learning materials package, technical video, including (Qt actual combat project, C++ language foundation, C++ design mode, 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↓↓

Qt5 string basic example

In the first example, we use some basic methods of the QString class.

basic.cpp
#include <QTextStream>
 
int main(void) {
 
   QTextStream out(stdout);
 
   QString a { "love" };
 
   a.append(" chess");
   a.prepend("I ");
 
   out << a << endl;
   out << "The a string has " << a.count()
       << " characters" << endl;
 
   out << a.toUpper() << endl;
   out << a.toLower() << endl;
 
   return 0;
}

In the code example, we initialized a QString. We append and prepend some additional text. We print the length of the string. Finally, we print the modified string in uppercase and lowercase.

QString a { "love" };

A QString is initialized.

a.append(" chess");
a.prepend("I ");

We append and prepend the text to the initial string. The string is modified in-place.

out << a << endl;

"I love chess" is printed to the terminal.

out << "The a string has " << a.count()
    << " characters" << endl;

The count method returns the number of characters in the string. The length and size methods are equivalent.

out << a.toUpper() << endl;
out << a.toLower() << endl;

These two methods return uppercase and lowercase copies of the string. They don't modify the string, they return a new modified copy of the string.

$ ./basic
I love chess
The a string has 12 characters
I LOVE CHESS
i love chess

Qt5 initialization string

A QString can be initialized in several ways.

init.cpp
#include <QTextStream>
 
int main(void) {
 
   QTextStream out(stdout);
 
   QString str1 = "The night train";
   out << str1 << endl;
 
   QString str2("A yellow rose");
   out << str2 << endl;
 
   QString str3 {"An old falcon"};
   out << str3 << endl;
 
   std::string s1 = "A blue sky";
   QString str4 = s1.c_str();
   out << str4 << endl;
 
   std::string s2 = "A thick fog";
   QString str5 = QString::fromLatin1(s2.data(), s2.size());
   out << str5 << endl;
 
   char s3[] = "A deep forest";
   QString str6(s3);
   out << str6 << endl;
 
   return 0;
}

We introduced five methods of initializing QString.

QString str1 = "The night train";

This is the traditional way of initializing strings in computer languages.

QString str2("A yellow rose");

This is the object method to initialize QString.

QString str3 {"An old falcon"};

This is brace initialization.

std::string s1 = "A blue sky";
QString str4 = s1.c_str();

We have a String object from the C++ standard library. We use its c_str method to generate a null-terminated character sequence. This character array is the classic C representation of a string and can be assigned to a QString variable.

std::string s2 = "A thick fog";
QString str5 = QString::fromLatin1(s2.data(), s2.size());

In these lines of code, we convert a standard C++ string to a QString. We use the fromLatin1 method. It takes a pointer to a character array. Pointers are returned with the data methods of std::string. The second parameter is the size of the std::string.

char s3[] = "A deep forest";
QString str6(s3);

This is a C string; it is an array of characters. One of the QString constructors can take a character array as a parameter.

$ ./init 
The night train
A yellow rose
An old falcon
A blue sky
A thick fog
A deep forest

Qt5 access to string elements

QString is a sequence of QChars. Elements of a string can be accessed using the [] operator or the at method.

access.cpp
#include <QTextStream>
 
int main(void) {
 
   QTextStream out(stdout);
 
   QString a { "Eagle" };
 
   out << a[0] << endl;
   out << a[4] << endl;
 
   out << a.at(0) << endl;
 
   if (a.at(5).isNull()) {
     out << "Outside the range of the string" << endl;
   }
 
   return 0;
}

We print some individual characters from a specific QString.

out << a[0] << endl;
out << a[4] << endl;

We print the first and fifth elements of the string.

out << a.at(0) << endl;

Using the at method, we retrieve the first character of the string.

if (a.at(5).isNull()) {
    out << "Outside the range of the string" << endl;
}

If we try to access characters outside the character range of the string, the at method will return null.

$ ./access
E
e
E
Outside the range of the string

Qt5 string length

Three ways to get the length of a string. Size, count and length methods. All do the same thing. They return the number of characters in the specified string.

length.cpp
#include <QTextStream>
 
int main(void) {
 
  QTextStream out(stdout);
 
  QString s1 = "Eagle";
  QString s2 = "Eagle\n";
  QString s3 = "Eagle ";
  QString s4 = "орел";
 
  out << s1.length() << endl;
  out << s2.length() << endl;
  out << s3.length() << endl;
  out << s4.length() << endl;
 
  return 0;
}

We get the size of four strings.

QString s2 = "Eagle\n";
QString s3 = "Eagle ";

Each of these two strings has a blank character.

QString s4 = "орел";

The string consists of Russian letters.

$ ./length
5
6
6
4

From the output we can see that the length method also counts whitespace characters.

Qt5 build string

Dynamic string construction allows us to replace specific control characters with actual values. We use the arg method for interpolation.

building.cpp
#include <QTextStream>
 
int main() {
 
   QTextStream out(stdout);
 
   QString s1 = "There are %1 white roses";
   int n = 12;
 
   out << s1.arg(n) << endl;
 
   QString s2 = "The tree is %1 m high";
   double h = 5.65;
 
   out << s2.arg(h) << endl;
 
   QString s3 = "We have %1 lemons and %2 oranges";
   int ln = 12;
   int on = 4;
 
   out << s3.arg(ln).arg(on) << endl;
 
   return 0;
}

The tokens to be replaced start with a % character. The following characters are numbers specifying the parameter. A string can have multiple parameters. The arg method is overloaded, it can accept integers, long numbers, characters and QChars etc.

QString s1 = "There are %1 white roses";
int n = 12;

%1 is the token we plan to replace. We define an integer.

out << s1.arg(n) << endl;

The arg method accepts an integer. The %1 token is replaced with the value of the n variable.

QString s2 = "The tree is %1 m high";
double h = 5.65;

out << s2.arg(h) << endl;

这三行对double做同样的事情。 自动调用正确的 arg 方法。
QString s3 = "We have %1 lemons and %2 oranges";
int ln = 12;
int on = 4;

out << s3.arg(ln).arg(on) << endl;

We can have multiple control characters. %1 refers to the first parameter, %2 refers to the second parameter. The arg method is called in a continuation chain.

The benefits of this article, free to receive Qt development learning materials package, technical video, including (Qt actual combat project, C++ language foundation, C++ design mode, 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↓↓

$ ./building
There are 12 white roses
The tree is 5.65 m high
We have 12 lemons and 4 oranges

Qt5 substring

When doing text processing, we need to find substrings of ordinary strings. We have left, mid and right methods at our disposal.

substrings.cpp
#include <QTextStream>
 
int main(void) {
 
   QTextStream out(stdout);
 
   QString str = { "The night train" };
 
   out << str.right(5) << endl;
   out << str.left(9) << endl;
   out << str.mid(4, 5) << endl;
 
   QString str2("The big apple");
   QStringRef sub(&str2, 0, 7);
 
   out << sub.toString() << endl;
 
   return 0;
}

We will use all three methods to find certain substrings of a given string.

out << str.right(5) << endl;

Using right, we get the rightmost five characters of the str string. "train" is printed.

out << str.left(9) << endl;

Using the left method, we get the leftmost nine characters of the str string. "The night" is printed.

out << str.mid(4, 5) << endl;

Using the mid method, we get five characters starting from the fourth position. prints "night".

QString str2("The big apple");
QStringRef sub(&str2, 0, 7);

The QStringRef class is a read-only version of QString. Here we create a QStringRef that is part of the str2 string. The second parameter is the position, and the third is the length of the substring.

$ ./substrings
train
The night
night
The big

Qt5 looping through a string

QStrings are composed of QChars. We can loop through the QString to access each element of the string.

looping.cpp
#include <QTextStream>
 
int main(void) {
 
  QTextStream out(stdout);
 
  QString str { "There are many stars." };
 
  for (QChar qc: str) {
    out << qc << " ";
  }
 
  out << endl;
 
  for (QChar *it=str.begin(); it!=str.end(); ++it) {
    out << *it << " " ;
  }
 
  out << endl;
 
  for (int i = 0; i < str.size(); ++i) {
    out << str.at(i) << " ";
  }
 
  out << endl;
 
  return 0;
}

We show three methods of traversing a QString. When we print them to the terminal, we add a space character between the letters.

for (QChar qc: str) {
  out << qc << " ";
}

We iterate through the string using a range-based for loop.

for (QChar *it=str.begin(); it!=str.end(); ++it) {
  out << *it << " " ;
}

In this code, we iterate through the string using an iterator.

for (int i = 0; i < str.size(); ++i) {
  out << str.at(i) << " ";
}
$ ./looping
T h e r e   a r e   m a n y   s t a r s .
T h e r e   a r e   m a n y   s t a r s .
T h e r e   a r e   m a n y   s t a r s .

Qt5 string comparison

The QString::compare static method is used to compare two strings. This method returns an integer. If the return value is less than zero, the first string is less than the second. If it returns zero, the two strings are equal. Finally, if the return value is greater than zero, the first string is greater than the second. "less" means that a specific character of the string precedes another character in the character table.

Strings are compared in the following way: the first characters of two strings are compared; if they are equal, the next two characters are compared until we find some characters that differ or we find that all characters match.

comparing.cpp
#include <QTextStream>
 
#define STR_EQUAL 0
 
int main(void) {
 
   QTextStream out(stdout);
 
   QString a { "Rain" };
   QString b { "rain" };
   QString c { "rain\n" };
 
   if (QString::compare(a, b) == STR_EQUAL) {
     out << "a, b are equal" << endl;
   } else {
     out << "a, b are not equal" << endl;
   }
 
   out << "In case insensitive comparison:" << endl;
 
   if (QString::compare(a, b, Qt::CaseInsensitive) == STR_EQUAL) {
     out << "a, b are equal" << endl;
   } else {
     out << "a, b are not equal" << endl;
   }
 
   if (QString::compare(b, c) == STR_EQUAL) {
     out << "b, c are equal" << endl;
   } else {
     out << "b, c are not equal" << endl;
   }
 
   c.chop(1);
 
   out << "After removing the new line character" << endl;
 
   if (QString::compare(b, c) == STR_EQUAL) {
     out << "b, c are equal" << endl;
   } else {
     out << "b, c are not equal" << endl;
   }
 
   return 0;
}

We'll use the Compare method for case-sensitive and case-insensitive comparisons.

#define STR_EQUAL 0

For better code clarity, we define the STR_EQUAL constant.

QString a { "Rain" };
QString b { "rain" };
QString c { "rain\n" };

We are comparing these three strings.

if (QString::compare(a, b) == STR_EQUAL) {
    out << "a, b are equal" << endl;
} else {
    out << "a, b are not equal" << endl;
}

We compare a and b strings, they are not equal. They differ on the first character.

if (QString::compare(a, b, Qt::CaseInsensitive) == STR_EQUAL) {
    out << "a, b are equal" << endl;
} else {
    out << "a, b are not equal" << endl;
}

Strings are equal in a case-insensitive comparison. Qt::CaseInsensitive makes the comparison case-insensitive.

c.chop(1);

The chop method removes the last character from a c string. Now the b and c strings are equal.

$ ./comparing
a, b are not equal
In case insensitive comparison:
a, b are equal
b, c are not equal
After removing the new line character
b, c are equal

Qt5 conversion string

Strings often need to be converted to other data types and vice versa. toInt, toFloat, toLong are three QString methods that convert strings to integers, floats, and longs. (There are many more such methods.) The setNum method converts various numeric data types to strings. Methods are overloaded and the correct method is called automatically.

converting.cpp
#include <QTextStream>
 
int main(void) {
 
  QTextStream out(stdout);
 
  QString s1 { "12" };
  QString s2 { "15" };
  QString s3, s4;
 
  out << s1.toInt() + s2.toInt() << endl;
 
  int n1 = 30;
  int n2 = 40;
 
  out << s3.setNum(n1) + s4.setNum(n2) << endl;
 
  return 0;
}

In the example we convert two strings to integers and add them. Then we convert the two integers to strings and concatenate them.

out << s1.toInt() + s2.toInt() << endl;

The toInt method converts a string to an integer. We add two numbers converted from strings.

out << s3.setNum(n1) + s4.setNum(n2) << endl;

In this case, the setNum method converts the integer to a string. We concatenate two strings.

$ ./converting
27
3040

letter

Characters are grouped into various categories: numbers, letters, spaces, and punctuation marks. Each QString is composed of QChars. QChar has isDigit, isLetter, isSpace and isPunct methods to get the job done.

letters.cpp
#include <QTextStream>
 
int main(void) {
 
  QTextStream out(stdout);
 
  int digits  = 0;
  int letters = 0;
  int spaces  = 0;
  int puncts  = 0;
 
  QString str { "7 white, 3 red roses." };
 
  for (QChar s : str) {
 
    if (s.isDigit()) {
      digits++;
    } else if (s.isLetter()) {
      letters++;
    } else if (s.isSpace()) {
      spaces++;
    } else if (s.isPunct()) {
      puncts++;
    }
  }
 
  out << QString("There are %1 characters").arg(str.count()) << endl;
  out << QString("There are %1 letters").arg(letters) << endl;
  out << QString("There are %1 digits").arg(digits) << endl;
  out << QString("There are %1 spaces").arg(spaces) << endl;
  out << QString("There are %1 punctuation characters").arg(puncts) << endl;
 
  return 0;
}

In this example, we define a simple sentence. We count the number of numbers, letters, spaces and punctuation in that sentence.

int digits  = 0;
int letters = 0;
int spaces  = 0;
int puncts  = 0;

We define an integer variable for each character class.

QString str { "7 white, 3 red roses." };

This is the sentence that needs to be checked.

for (QChar s : str) {

  if (s.isDigit()) {
    digits++;
  } else if (s.isLetter()) {
    letters++;
  } else if (s.isSpace()) {
    spaces++;
  } else if (s.isPunct()) {
    puncts++;
  }
}

We use a for-range based loop to browse the QString. Each element is a QChar. We use the methods of the QChar class to determine the character's category.

out << QString("There are %1 characters").arg(str.count()) << endl;
out << QString("There are %1 letters").arg(letters) << endl;
out << QString("There are %1 digits").arg(digits) << endl;
out << QString("There are %1 spaces").arg(spaces) << endl;
out << QString("There are %1 punctuation characters").arg(puncts) << endl;

Using string interpolation, we print these numbers to the terminal.

$ ./letters
There are 21 characters
There are 13 letters
There are 2 digits
There are 4 spaces
There are 2 punctuation characters

Qt5 modify string

Some methods (such as the toLower method) return a new, modified copy of the original string. Other methods modify the string in place. We introduce some of them.

modify.cpp
#include <QTextStream>
 
int main(void) {
 
   QTextStream out(stdout);
 
   QString str { "Lovely" };
   str.append(" season");
 
   out << str << endl;
 
   str.remove(10, 3);
   out << str << endl;
 
   str.replace(7, 3, "girl");
   out << str << endl;
 
   str.clear();
 
   if (str.isEmpty()) {
     out << "The string is empty" << endl;
   }
 
   return 0;
}

We describe four methods for modifying strings in place.

str. append("season").
The append method adds a new string at the end of the string.

str.remove(10, 3);
The remove method removes 3 characters from the string, starting from the 10th.

str.replace(7, 3, "girl");
The replacement method replaces the 3 characters starting from position 7 with the specified string.

str.clear();
The clear method clears the string.

$ ./modify
Lovely season
Lovely sea
Lovely girl
The string is empty

Qt5 align string

Having a tidy output is a common requirement. We can use the leftJustified and rightJustified methods to justify our strings.

right_align.cpp
#include <QTextStream>
 
int main(void) {
 
   QTextStream out(stdout);
 
   QString field1 { "Name: " }; 
   QString field2 { "Occupation: " }; 
   QString field3 { "Residence: " }; 
   QString field4 { "Marital status: " }; 
 
   int width = field4.size();
 
   out << field1.rightJustified(width, ' ') << "Robert\n";
   out << field2.rightJustified(width, ' ') << "programmer\n";
   out << field3.rightJustified(width, ' ') << "New York\n";
   out << field4.rightJustified(width, ' ') << "single\n";
 
   return 0;
}

This example aligns field strings to the right.

int width = field4. size().
We calculate the size of the widest string.

out << field1.rightJustified(width, ' ') << "Robert\n";
The rightJustified method returns a string with width characters. If the string is shorter, the remainder is filled with the provided characters. In our case, it is a space character.

$ ./right_align
          Name: Robert
    Occupation: programmer
     Residence: New York
Marital status: single

Qt5 escape character

Qt5 has a toHtmlEscaped method that converts a plain text string to an HTML string and replaces HTML metacharacters <, >, &, and " with HTML named entities.

$ cat cprog.c
#include <stdio.h>
 
int main(void) {
 
    for (int i=1; i<=10; i++) {
      
        printf("Bottle %d\n", i);
    }
}

This C language program includes HTML metacharacters.

html_escape.cpp
#include <QTextStream>
#include <QFile>
 
int main(void) {
 
    QTextStream out(stdout);
 
    QFile file("cprog.c");
 
    if (!file.open(QIODevice::ReadOnly)) {
 
        qWarning("Cannot open file for reading");
        return 1;
    }
 
    QTextStream in(&file);
 
    QString allText = in.readAll();
    out << allText.toHtmlEscaped() << endl;
 
    file.close();
 
    return 0;
}

This example reads a C program and replaces metacharacters with their named entities.

The benefits of this article, free to receive Qt development learning materials package, technical video, including (Qt actual combat project, C++ language foundation, C++ design mode, 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/m0_73443478/article/details/132560655