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

How to convert unicode characters to uppercase in C++

我正在学习 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] = '[=10=]';
    std::cout << toupper(name) << std::endl;
}

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


(编辑:好的,所以我阅读了更多关于标准 C++ here 中的 unicode 支持的信息。看来我最好的选择是使用 ICU 或Boost.locale 用于此任务。C++ 本质上将 std::string 视为一团二进制数据,因此正确大写 unicode 字母似乎不是一件容易的事。我认为我的 hacky 解决方案使用 uint64_t 在任何方面都不比 C++ 标准库更有用,甚至更糟。如果能提供一个关于如何使用 ICU 实现上述行为的示例,我将不胜感激。)

看看ICU User Guide. For simple (single-character) case mapping, you can use u_toupper. For full case mapping, use 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;
}

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