const char8_t*转string
时间: 2023-12-22 11:14:03 浏览: 45
将const char8_t*类型的字符串转换为std::string类型的字符串,可以使用std::wstring_convert模板类进行转换,具体步骤如下:
1. 将const char8_t*类型的字符串转换为std::u32string类型的字符串,可以使用std::basic_string_view<char8_t>类的构造函数,将const char8_t*类型的字符串作为参数传入,然后再使用std::u32string类的构造函数,将basic_string_view<char8_t>类型的字符串转换为std::u32string类型的字符串。
2. 将std::u32string类型的字符串转换为std::wstring类型的字符串,可以使用std::wstring_convert模板类进行转换,具体步骤如下:
- 创建一个std::wstring_convert对象,指定转换的字符编码类型为UTF-32和本地编码类型;
- 调用std::wstring_convert对象的to_bytes()方法,将std::u32string类型的字符串转换为std::string类型的字符串。
下面是示例代码:
```c++
#include <iostream>
#include <string>
#include <string_view>
#include <locale>
#include <codecvt>
using namespace std;
string u8string_to_string(const char8_t* u8str)
{
// 将const char8_t*类型的字符串转换为std::u32string类型的字符串
std::u32string u32str = std::u32string{u8str};
// 将std::u32string类型的字符串转换为std::string类型的字符串
std::wstring_convert<std::codecvt_utf8<int32_t>, int32_t> cvt;
return cvt.to_bytes(u32str);
}
int main()
{
const char8_t* u8str = u8"Hello, world! 你好,世界!";
std::string str = u8string_to_string(u8str);
std::cout << str << std::endl;
return 0;
}
```
在上面的示例代码中,我们将const char8_t*类型的字符串转换为std::string类型的字符串,首先将const char8_t*类型的字符串转换为std::u32string类型的字符串,然后再使用std::wstring_convert模板类将std::u32string类型的字符串转换为std::string类型的字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.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)