如何将string转成char8
时间: 2023-12-28 14:04:16 浏览: 25
在 C++20 及以上版本中,可以使用 `std::u8string` 类型表示 UTF-8 字符串,因此可以直接将 `std::string` 转换成 `std::u8string` 类型。例如:
```c++
#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string str = "hello, world!";
std::u8string u8str(str.begin(), str.end());
std::cout << u8str << std::endl;
return 0;
}
```
如果你使用的是旧版本的 C++,可以使用一些库(如 iconv、libiconv、Boost.Locale 等)来进行字符编码转换。例如,使用 libiconv 库:
```c++
#include <iostream>
#include <string>
#include <iconv.h>
int main() {
std::string str = "hello, world!";
std::string out_str(1024, '\0');
char *in_buf = const_cast<char*>(str.c_str());
char *out_buf = &out_str[0];
size_t in_size = str.size();
size_t out_size = out_str.size();
iconv_t cd = iconv_open("UTF-8", "ISO-8859-1");
iconv(cd, &in_buf, &in_size, &out_buf, &out_size);
iconv_close(cd);
out_str.resize(out_str.size() - out_size);
std::cout << out_str << std::endl;
return 0;
}
```
注意,在使用字符编码转换库时,需要确保源字符串和目标字符串的编码格式正确,否则可能会得到错误的结果。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)