如何使用ICU在C ++中将Unicode代码点转换为字符?

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

以某种方式我无法在Google中找到答案。搜索时可能使用了错误的术语。我正在尝试执行一个简单的任务,将代表字符的数字转换为字符本身,如下表所示:http://unicode-table.com/en/#0460

例如,如果我的电话号码是47(即'\'),我可以将47放在char中并使用cout打印,然后我会在控制台中看到一个反斜杠(对于小于256的数字)。

但是如果我的电话号码是1120,则字符应为'Ѡ'(拉丁语为Ω)。我假设它由几个字符表示(cout在打印到屏幕时会知道会转换为“Ѡ”)。

如何获得代表“Ѡ”的“几个字符”?

我有一个名为ICU的库,并且我正在使用UTF-8。

c++ unicode icu
2个回答
7
投票

您所说的Unicode数字通常称为代码点。如果要使用C ++和Unicode字符串,ICU提供<< icu :: UnicodeString类。您可以find the documentation here

要创建一个包含单个字符的

UnicodeString

,可以使用constructor that takes a code point in a UChar32icu::UnicodeString::UnicodeString(UChar32 ch)
然后您可以调用toUTF8String方法将字符串转换为UTF-8。

示例程序:

#include <iostream> #include <string> #include <unicode/unistr.h> int main() { icu::UnicodeString uni_str((UChar32)1120); std::string str; uni_str.toUTF8String(str); std::cout << str << std::endl; return 0; }

在类似Debian的Linux系统上,您可以使用以下程序编译该程序:

g++ so.cc -o so -licuuc

如果您的终端支持UTF-8,将打印一个欧米茄字符。    

1
投票
注意:如果您遇到错误:'对icudt67_dat的未定义引用,您需要链接-licudt,那么您的问题将得到解决。
© www.soinside.com 2019 - 2024. All rights reserved.