C++跨平台的,极简洁的多字节与宽字节字符串互转代码

有点歪门邪道,但的确很简洁,且跨平台,需 C++ 17。

///<summary>多字节字符串转宽字节字符串 (仅 C++17, 需 #include string/filesystem)</summary>
///<param name="sText">多字节字符串</param>
///<param name="bUtf8">源多字符串是否 UTF-8 编码,否则是 ANSI 编码</param>
///<returns>宽字节字符串</returns>
std::wstring M2W(const char* sText, bool bUtf8)
{
	if (sText != nullptr && *sText != '\0')
	{
		try
		{
			if (bUtf8)
				return std::filesystem::u8path(sText).wstring();
			else
				return std::filesystem::path(sText).wstring();
		}
		catch (const std::exception&) {}
	}

	return L"";
}

///<summary>宽字节字符串转多字节字符串 (仅 C++17, 需 #include string/filesystem)</summary>
///<param name="sText">宽字节字符串</param>
///<param name="bUtf8">是否转换成 UTF-8 编码,否则转换成 ANSI 编码</param>
///<returns>UTF-8 或 ANSI 编码的多字节字符串</returns>
std::string W2M(const wchar_t* sText, bool bUtf8)
{
	if (sText != nullptr && *sText != L'\0')
	{
		try
		{
			if (bUtf8)
				return std::filesystem::path(sText).u8string();
			else
				return std::filesystem::path(sText).string();
		}
		catch (const std::exception&) {}
	}

	return "";
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值