The connection and mutual conversion between QString, std::string and const char* in Qt

introduction:

String manipulation is a very common task in Qt development. Qt provides the QString class to handle Unicode strings, and std::string in the standard C++ library is a common choice for handling ASCII strings. Also, C-style const char* is often used to interface with other libraries. In this article, we'll explore how all three are connected and how to convert between them.

mutual conversion

Conversion between QString and std::string

Both QString and std::string are classes used to represent strings, and the conversion between them can be achieved by the following methods:

QString to std::string: You can use QString's toStdString() method to convert QString to std::string. The sample code is as follows:

QString qstr = "Hello, world!";
std::string str = qstr.toStdString();

std::string to QString: You can use QString's fromStdString() method to convert std::string to QString. The sample code is as follows:

std::string str = "Hello, world!";
QString qstr = QString::fromStdString(str);

Conversion between QString and const char

When interacting with C-style libraries, we usually need to convert QString to const char, or convert const char* to QString. Here are two conversion methods:

QString to const char*: You can use QString's toUtf8() or toLatin1() method to convert QString to const char*. The sample code is as follows:

QString qstr = "Hello, world!";
const char* cstr = qstr.toUtf8().constData(); // 使用toLatin1()也可以

Convert const char to QString: You can use the fromUtf8() or fromLatin1() method of QString to convert const char to QString. The sample code is as follows:

const char* cstr = "Hello, world!";
QString qstr = QString::fromUtf8(cstr); // 使用fromLatin1()也可以

Conversion between std::string and const char

If you need to convert between std::string and const char, you can use the c_str() method of std::string to get the string represented by const char, or use the constructor of std::string to convert const char to std: :string. The sample code is as follows:

std::string to const char*:

std::string str = "Hello, world!";
const char* cstr = str.c_str();

const char* to std::string:

const char* cstr = "Hello, world!";
std::string str(cstr);

in conclusion:

The conversion between QString, std::string and const char* in Qt provides a convenient string processing tool. We can convert between them as needed, so as to better meet different development needs. In practical applications, it is necessary to select an appropriate transcoder according to the encoding type and requirements of the string.

Guess you like

Origin blog.csdn.net/qq_46017342/article/details/131159272