如何使用ICU将Unicode代码点转换为C++中的字符
How to convert a Unicode code point to characters in C++ using ICU?
不知怎么的,我在谷歌上找不到答案。可能我在搜索时使用了错误的术语。我试图执行一个简单的任务,将代表字符的数字转换为字符本身,如下表所示:http://unicode-table.com/en/#0460
例如,如果我的数字是47(即"\"),我只需将47放在char
中,然后使用cout
打印它,我就会在控制台中看到一个反斜杠(对于低于256的数字来说没有问题)。
但如果我的数字是1120,字符应该是"Ѡ"(拉丁语中的omega)。我假设它由几个字符表示(当它打印到屏幕上时,cout
会知道将其转换为"Ѡ")。
我如何获得这些代表"Ѡ"的"几个字符"?
我有一个名为ICU的库,我使用UTF-8。
您所称的Unicode编号通常被称为代码点。如果您想使用C++和Unicode字符串,ICU提供了一个ICU::UnicodeString类。你可以在这里找到文档。
要创建包含单个字符的UnicodeString,可以使用在UChar32中获取代码点的构造函数:
icu::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,这将打印一个omega字符。
另一种选择是只使用标准组件。以下示例将Unicode代码点视为std::u32string
,并将其返回为std::string
。
创建具有Unicode代码点的std::u32string
很简单:
方法1:使用大括号init(调用`initializer_list ctor)
std::u32string u1{codePointNumber};
// For example:
std::u32string u1{305}; // 305 is 'ı'
方法2:使用运算符+=
std::u32string u2{}; // Empty string
// For example:
u2 += 305;
要将std::u32string
转换为std::string
,可以使用<locale>
标头中的std::wstring_convert
:
#include <iostream>
#include <codecvt>
#include <string>
#include <locale>
std::string U32ToStr(const std::u32string& str)
{
std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> conv;
return conv.to_bytes(str);
}
int main()
{
std::u32string u1{305};
std::cout << U32ToStr(u1) << "n";
return 0;
}
来自goldbold 的示例1
请注意,std::wstring_convert
在C++17及更高版本中已弃用(但尚未删除),因此如果您使用的是较新版本的C++,则可能需要使用其他方法。
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 为什么 Serial.println(<char[]>);返回随机字符?
- 我的字符计数代码计算错误.为什么
- 字符串-C++后显示的随机字符
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 如何在C++中从字符串中分割字符
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 指向指向字符数组的指针数组的指针
- 如何用转义符替换字符串中的所有特殊字符
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 比较字符数组
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++中无符号字符溢出
- 使用无符号字符数组有效存储内存