0

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

3
  • Have you tried to use the debugger to view the inner content of these string? Commented Oct 14, 2016 at 8:43
  • @Danh yes, its what it shoud be "Présenter" thanks thou Commented Oct 14, 2016 at 8:43
  • This discussion might be interesting because the string encoding in your code might also play a role: Using Unicode in C++ source code Commented Oct 14, 2016 at 8:53

1 Answer 1

3

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)){ 
Sign up to request clarification or add additional context in comments.

14 Comments

I don't think QString::fromUtf8 will help. QString::operator== said that: The other byte array is converted to a QString using the fromUtf8() function.
@Danh I recall having this exact problem fixed by doing this back in the Qt 4 days. But it seems you're right.
Normalization is critical. Choosing the right normalization is also important.
@krzaq in the old day, The other const char pointer is converted to a QString using the fromAscii() function. as stated here And this question is tagged Qt 5.7
@aladin8848 I keep a habit to always save file in UTF-8 w/o BOM encoding
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.