advantage of QString over std::string
Solution 1
QString
allows you to work with Unicode, has more useful methods and integrates with Qt well. It also has better performance, as cbamber85 noted.
std::string
just stores the bytes as you give them to it, it doesn't know anything about encodings. It uses one byte per character, but it's not enough for all the languages in the world. The best way to store your texts would probably be UTF-8 encoding, in which characters can take up different number of bytes, and std::string
just can't handle that properly! This, for example, means that length
method would return the number of bytes, not characters. And this is just the tip of an iceberg...
Solution 2
If you are using Qt framework for writing your software then you are better off using QString. The simple reason being that almost all Qt functions that work on strings will accept QString. If you use std::string you might end up in situations where you will have to typecase from one to another. You should consider using std::string if your software is not using Qt at all. That will make your code more portable and not dependent on an extra framework that users will have to install to use your software.
Solution 3
I'm not familiar with QString
, but the big advantage of std::string
is that it is standard. With regards to Unicode, there's no problem
storing UTF-8 in an std::string
; depending on what you're doing,
however, it might be better to use a std::wstring
(which typically
will store either UTF-16 or UTF-32).
For complex manipulations of Unicode, I would suggest ICU. But for a lot of applications, just storing UTF-8 is sufficient.
Solution 4
Technically, there is a standard string class to store any type of character: std::basic_string
. std::string
and std::wstring
are nothing but specializations of std::basic_string
for char
and wchar
. There are also the specializations std::u16string
and std::u32string
that are meant for UTF-16 and UTF-32 storage.
Anyway, if you have to work with Qt, QString
will probably always be a better alternative than any standard library string since the whole Qt framework is designed to work with it.
Vihaan Verma
Updated on May 19, 2020Comments
-
Vihaan Verma almost 4 years
What advantages does QString offer over std::string? Can a normal std::string store unicode characters ? I m trying to write a program that will open various song files . The name of these files can be in different languages. I have heard that using a normal string in such cases will not work properly. I want to keep the application independent of QT and reuse the code for example in android . What do you suggest .