aladin8848 aladin8848 - 1 month ago 22
C++ Question

Comparing international strings

What I am trying to do is comparin 2 QStrings that have special characters (French)

first I recieved from server as json data saved in txtInfo

txtInfo = "Présenter";


When I am having condition like this it's not gonna work(its not gonna set state.)

if (txtInfo == "Présenter"){
m_appState = 8;
m_appStateString = AppStatesArray[m_appState];
}

else {
m_appState = -1;
m_appStateString = "UNKNOWN";
}


What I am missing? What if I would like to compare not French but Chinese?

Thank you very much

Answer

Since Qt 5 QString's operator== performs fromUtf8 conversion on the character array being compared to it. But if your source file (.cpp) isn't using utf8 you need to build your own QString.

Depending on your source file's (.cpp) encoding:

Utf8:

QString compared = QString::fromUtf8("Présenter");
if (txtInfo == QString::fromUtf8("Présenter")){

local 8-bit:

QString compared = QString::fromLocal8Bit("Présenter");
if (txtInfo == QString::fromUtf8("Présenter")){

For 100% correctness, don't forget to normalize your strings:

txtInfo = txtInfo.normalized(QString::NormalizationForm_D);
QString compared = /* the correct form for you */;
if (txtInfo == compared.normalized(QString::NormalizationForm_D)){