如何在C ++中将unicode字符转换为大写

问题描述 投票:2回答:2

我正在学习C ++中的unicode,我很难让它正常工作。我尝试将单个字符视为uint64_t。它的工作原理如果我需要它是打印字符,但问题是我需要将它们转换为大写。我可以将大写字母存储在数组中,只需使用与小写字母相同的索引,但我正在寻找更优雅的解决方案。我发现这个类似question,但大多数答案使用宽字符,这不是我可以使用的东西。这是我尝试过的:

#include <iostream>
#include <locale>
#include <string>
#include <cstdint>
#include <algorithm>

// hacky solution to store a multibyte character in a uint64_t
#define E(c) ((((uint64_t) 0 | (uint32_t) c[0]) << 32) | (uint32_t) c[1])

typedef std::string::value_type char_t;
char_t upcase(char_t ch) {
    return std::use_facet<std::ctype<char_t>>(std::locale()).toupper(ch);
}

std::string toupper(const std::string &src) {
    std::string result;
    std::transform(src.begin(), src.end(), std::back_inserter(result), upcase);
    return result;
}

const uint64_t VOWS_EXTRA[]
{
E("å")  , E("ä"), E("ö"), E("ij"), E("ø"), E("æ")
};

int main(void) {
    char name[5];
    std::locale::global(std::locale("sv_SE.UTF8"));
    name[0] = (VOWS_EXTRA[3] >> 32) & ~((uint32_t)0);
    name[1] = VOWS_EXTRA[3] & ~((uint32_t)0);
    name[2] = '\0';
    std::cout << toupper(name) << std::endl;
}

我希望这打印出字符IJ,但实际上它打印出与开头相同的字符(ij)。


(编辑:好的,所以我在标准C ++ here中阅读了更多关于unicode支持的内容。似乎我最好的选择是使用ICU或Boost.locale这样的任务.C ++本质上将std :: string视为二进制blob对于大写unicode字母来说,数据似乎并不是一件容易的事。我认为使用uint64_t的hacky解决方案在没有任何方面比C ++标准库更有用,如果不是更糟的话。我会感激关于如何使用ICU实现上述行为的示例。)

c++ c++11 unicode locale uppercase
2个回答
2
投票

看看ICU User Guide。对于简单(单字符)大小写映射,您可以使用u_toupper。对于完整案例映射,请使用u_strToUpper。示例代码:

#include <unicode/uchar.h>
#include <unicode/ustdio.h>
#include <unicode/ustring.h>

int main() {
    UChar32 upper = u_toupper(U'ij');
    u_printf("%lC\n", upper);

    UChar src = u'ß';
    UChar dest[3];
    UErrorCode err = U_ZERO_ERROR;
    u_strToUpper(dest, 3, &src, 1, NULL, &err);
    u_printf("%S\n", dest);

    return 0;
}

0
投票

如果有人在寻找它,std::towupperstd::towlower似乎工作正常https://en.cppreference.com/w/cpp/string/wide/towupper

© www.soinside.com 2019 - 2024. All rights reserved.