转换unicode字符串,反之亦然

use*_*241 14 c++ unicode

我对使用Unicode字符串和指针有点新意,我不知道如何将转换为unicode转换为ascii,反之亦然.以下是我正在尝试做的事情,

const wchar_t *p = L"This is a string";
Run Code Online (Sandbox Code Playgroud)

如果我想将其转换为char*,转换如何转换wchar_t*char*反之亦然?

或者通过使用类对象的值wstring,string反之亦然

std::wstring wstr = L"This is a string";
Run Code Online (Sandbox Code Playgroud)

如果我是正确的,您可以将字符串复制到新缓冲区而不进行转换吗?

Phi*_*ipp 22

在未来(VS 2010已经支持它),这将在标准C++中实现(最终!):

#include <string>
#include <locale>

std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
const std::wstring wide_string = L"This is a string";
const std::string utf8_string = converter.to_bytes(wide_string);
Run Code Online (Sandbox Code Playgroud)

  • 我认为最后一行中有一个拼写错误的`std :: wstring`应该是`std:string` (4认同)

MSa*_*ers 5

从 ASCII 到 Unicode 以及从 ASCII 到 Unicode 的转换非常简单。按照设计,前 128 个 Unicode 值与 ASCII 相同(实际上,前 256 个等于 ISO-8859-1)。

因此,以下代码适用于charASCII 和wchar_tUnicode 的系统:

const char* ASCII = "Hello, world";
std::wstring Unicode(ASCII, ASCII+strlen(ASCII));
Run Code Online (Sandbox Code Playgroud)

你不能这么简单地扭转它:?确实存在于 Unicode 中,但不存在于 ASCII 中,那么您将如何“转换”它?


Eug*_*its 3

这些解决方案依赖于平台。在 Windows 上使用MultiByteToWideCharWideCharToMultiByte API 函数。在 Unix/linux 平台上iconv库非常流行。