std::string 字符串编码转换
时间: 2023-11-15 16:06:41 浏览: 82
可以使用iconv库将一个字符集编码转换成另一个字符集编码,其中iconv_open()函数用于初始化一个字符集编码转换描述符,iconv()函数用于进行实际的字符集编码转换,iconv_close()函数用于关闭字符集编码转换描述符。下面是一个示例代码:
```
#include <iconv.h>
#include <string.h>
int convert_encoding(const char* from_charset, const char* to_charset,
const char* inbuf, size_t inlen, char* outbuf, size_t outlen) {
iconv_t cd = iconv_open(to_charset, from_charset);
if (cd == (iconv_t)-1) {
return -1;
}
char* inbuf_ptr = const_cast<char*>(inbuf);
char* outbuf_ptr = outbuf;
size_t outlen_left = outlen;
size_t rc = iconv(cd, &inbuf_ptr, &inlen, &outbuf_ptr, &outlen_left);
iconv_close(cd);
if (rc == (size_t)-1) {
return -1;
}
return outlen - outlen_left;
}
int main() {
const char* utf8_str = "你好世界";
char utf16_str[32];
int rc = convert_encoding("UTF-8", "UTF-16", utf8_str, strlen(utf8_str), utf16_str, sizeof(utf16_str));
if (rc == -1) {
printf("convert failed\n");
return -1;
}
utf16_str[rc] = '\0';
printf("%d %s\n", rc, utf16_str);
return 0;
}
```
阅读全文