跳到主要内容

字符串处理

wstring 是什么?

wstring 是宽字符,占用2个字节的大小,针对UNICODE编码格式,用于对中文汉字的定义和赋值。wstring跟string区别为:字节不同、编码格式不同、使用不同。

一、字节不同

  • wstring:是宽字符,占用 2 个字节的大小,即 16bit。
  • string:是窄字符,占用 1 个字节的大小,即 8bit。

也就是说,宽字符,每表示一个字符其实是占了 16bit,即 2 个 char 的大小。而汉字就是需要 16bit 来表示。

二、编码格式不同

  • wstring:一般针对 UNICODE 编码格式,一个单元两个 char。
  • string:一般针对 ASCII 编码格式,一个单元一个 char。

三、使用不同

  • wstring:在使用中文汉字时,使用 wstring 来定义变量进行赋值。
  • string:在使用英文汉字时,使用 string 来定义变量进行赋值。
#include <string>
#include <codecvt> // 编码转换

// string utf-8 与 wstring utf-16 的双向转换器
std::wstring_convert<std::codecvt_utf8<wchar_t>> conv_Ustr_Wstr;


// 专门用于消息的 wstring 转 string,转换失败时返回默认提示文字
string msg_wstr_2_ustr(wstring& msg) {
try {
string msgU8 = conv_Ustr_Wstr.to_bytes(msg); // 转回 u8
return msgU8;
} catch (...) {
return "wstring failed to convert to utf-8 string";
}
}