从QString中提取字符并进行比较

时间:2016-05-19 11:35:08

标签: c++ character stdstring qstring

我试图比较QString中的特定字符,但得到奇怪的结果:

我的名为strModified的QString包含:“[y]£trainstrip + [height]£trainstrip + 8”

我将字符串转换为标准字符串:

    std:string stdstr = strModified.toStdString();

我可以在调试器中看到'stdstr'包含正确的内容,但是当我尝试提取一个字符时:

    char cCheck = stdstr.c_str()[3];

我得到的东西完全不同,我希望看到'£',但我得到-62。我意识到'£'在ASCII字符集之外,代码为156。

但它又回来了什么?

我已经修改了原始代码以简化,现在:

    const QChar cCheck = strModified.at(intClB + 1);

    if ( cCheck == mccAttrMacroDelimited ) {
       ...
    }

mccAttrMacroDelimited定义为:

   const QChar clsXMLnode::mccAttrMacroDelimiter = '£';

在调试器中查看两个应该是相同值的定义时,我得到:

   cCheck: -93 '£'
   mccAttrMacroDelimiter:  -93 with what looks like a chinese character

比较失败了......发生了什么事?

我已经完成了我的代码,将所有QChar引用更改为unsigned char,现在我收到警告:

    large integer implicitly truncated to unsigned type [-Woverflow]

在:

    const unsigned char clsXMLnode::mcucAttrMacroDelimiter = '£';

再次,为什么?根据谷歌搜索,这可能是一个虚假的消息。

2 个答案:

答案 0 :(得分:0)

我很高兴地说这解决了问题,解决方案,将检查字符声明为unsigned char并使用:

    const char cCheck = strModified.at(intClB + 1).toLatin1();

答案 1 :(得分:0)

我认为因为'£'不是ASCII表,你会从'char'得到奇怪的行为。 Xcode中的编译器甚至不让我编译

char c = '£'; error-> character too large for enclosing literal type

您可以使用unicode,因为可以在Unicode字符表中找到'£' £:你+ 00A3 |十二月:163。

The answer to this question激发了我编写的代码以提取“£”的小数值。

#include <iostream>
#include <codecvt>
#include <locale>
#include <string>

using namespace std;

//this takes the character at [index] and prints the unicode decimal value
u32string foo(std::string const & utf8str, int index)
{
  std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> conv;
  std::u32string utf32str = conv.from_bytes(utf8str);

  char32_t u = utf32str[index];
  cout << u << endl;
  return &u;
}

int main(int argc, const char * argv[]) {
  string r = "[y]£trainstrip+[height]£trainstrip+8";

  //compare the characters at indices 3 and 23 since they are the same
  cout << (foo(r,3) == foo(r, 23)) << endl;

  return 0;
}

如果需要,可以使用for循环来获取字符串中的所有字符。希望这有助于