c++17 取字符的unicode
时间: 2023-09-10 21:08:39 浏览: 38
在 C++17 中,可以使用 `std::u32string_view` 类型来表示 Unicode 字符串,并且提供了 `std::u32string_view::operator[]` 方法来访问字符串中的单个字符。这个方法返回的是一个 `char32_t` 类型的值,表示 Unicode 编码的字符。
以下是一个示例代码,演示如何使用 `std::u32string_view` 来访问 Unicode 字符串中的单个字符:
```c++
#include <iostream>
#include <string_view>
int main() {
std::u32string_view str = U"Hello, 世界!";
for (std::size_t i = 0; i < str.size(); ++i) {
std::cout << "Character at index " << i << " is " << str[i] << std::endl;
}
return 0;
}
```
输出结果为:
```
Character at index 0 is 72
Character at index 1 is 101
Character at index 2 is 108
Character at index 3 is 108
Character at index 4 is 111
Character at index 5 is 44
Character at index 6 is 32
Character at index 7 is 19990
Character at index 8 is 30028
Character at index 9 is 33
```
可以看到,`str[i]` 返回的是该字符的 Unicode 编码值,而不是该字符本身。如果需要将 Unicode 编码值转换为字符本身,可以使用相应的转换方法,比如 `std::wstring_convert`、`std::codecvt_utf8` 等。