C++实现字符格式相互转换的示例代码

   2023-02-09 学习力0
核心提示:目录一、UTF8转std:string二、string_To_UTF8三、wstring转string四、string转wstring五、unicode属性和多字节属性转换(char转wchar_t)六、Unicode ansi utf8转换一、UTF8转std:stringstd::string UTF8_To_string(const std::string str){int nwLen = Multi

一、UTF8转std:string

std::string UTF8_To_string(const std::string& str)
{
	int nwLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
	wchar_t* pwBuf = new wchar_t[nwLen + 1];    //一定要加1,不然会出现尾巴 
	memset(pwBuf, 0, nwLen * 2 + 2);
	MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), pwBuf, nwLen);
	int nLen = WideCharToMultiByte(CP_ACP, 0, pwBuf, -1, NULL, NULL, NULL, NULL);
	char* pBuf = new char[nLen + 1];
	memset(pBuf, 0, nLen + 1);
	WideCharToMultiByte(CP_ACP, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);

	std::string strRet = pBuf;

	delete[]pBuf;
	delete[]pwBuf;
	pBuf = NULL;
	pwBuf = NULL;

	return strRet;
}

二、string_To_UTF8

std::string string_To_UTF8(const std::string& str)
{
	int nwLen = ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);
	wchar_t* pwBuf = new wchar_t[nwLen + 1];    //一定要加1,不然会出现尾巴 
	ZeroMemory(pwBuf, nwLen * 2 + 2);
	::MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.length(), pwBuf, nwLen);
	int nLen = ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, -1, NULL, NULL, NULL, NULL);
	char* pBuf = new char[nLen + 1];
	ZeroMemory(pBuf, nLen + 1);
	::WideCharToMultiByte(CP_UTF8, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);

	std::string strRet(pBuf);

	delete[]pwBuf;
	delete[]pBuf;
	pwBuf = NULL;
	pBuf = NULL;

	return strRet;
}

三、wstring转string

std::string wstring2string(std::wstring wstr)
{
	string result;
	int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL);
	if (len <= 0)return result;
	char* buffer = new char[len + 1];
	if (buffer == NULL)return result;
	WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL);
	buffer[len] = '\0';
	result.append(buffer);
	delete[] buffer;
	return result;
}

四、string转wstring

std::wstring  string2wstring(std::string str)
{
	wstring result;
	int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0);
	if (len < 0)return result;
	wchar_t* buffer = new wchar_t[len + 1];
	if (buffer == NULL)return result;
	MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len);
	buffer[len] = '\0';
	result.append(buffer);
	delete[] buffer;
	return result;
}

五、unicode属性和多字节属性转换(char转wchar_t)

// WideChar.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include <windows.h>
#include <iostream>
#include <atlbase.h>
//#include <comutil.h>
#include <atlstr.h>
using namespace std;

//方法1:MultiByteToWideChar, WideCharToMultiByte
void Way_1()
{
	//char转wchar_t
	char *p1 = "abc";
	wchar_t p2[20] = L"EFG";
	MultiByteToWideChar(CP_ACP, 0, p1, strlen(p1) + 1, p2, sizeof(p2));
	printf("%S\n", p2);

	//wchar_t转char
	wchar_t *p3= L"EFG";
	char p4[20];
	WideCharToMultiByte(CP_ACP, 0, p3, -1, p4, sizeof(p4), NULL, NULL);
	printf("%s\n", p4);

}

//方法2:A2W, W2A, T2A, A2T
void Way_2()
{
	//需要添加头文件 <atlbase.h>
	char * p1 = "abc";
	wchar_t *p2 = L"def";
	TCHAR *P3 = _T("CC");

	USES_CONVERSION;
	wchar_t *p5 = A2W(p1);
	char * p4 = T2A(P3);
}

方法3:
//void Way_3()
//{//需要添加头文件<comutil.h>,一般在MFC工程下使用
//	CString str = "abc";//只能存一种
//	_bstr_t bstr = "abc";//可以用非unicode
//	bstr += L"efg";//可以用unicode
//	char *p = bstr;
//	wchar_t *p2 = bstr;
//}

int main()
{
	Way_1();
	//Way_2();

	return 0;
}

六、Unicode ansi utf8转换

int Unicode2UTF8(const wchar_t* pUnicode, char* pUTF8Buffer, int nBufferSize)
{
	if( (nBufferSize == 0) && (pUTF8Buffer != NULL) )
		return 0;

	int result = WideCharToMultiByte(CP_UTF8, NULL, pUnicode, -1, pUTF8Buffer, nBufferSize, NULL, NULL);
	if ((result > 0) && (pUTF8Buffer != NULL))
		pUTF8Buffer[result-1] = 0;

	return result;
}

int UTF82Unicode(const char* pUTF8, wchar_t* pUnicodeBuffer, int nBufferSize)
{
	if( (nBufferSize == 0) && (pUnicodeBuffer != NULL) )
		return 0;

	int result = MultiByteToWideChar(CP_UTF8, NULL, pUTF8, -1, pUnicodeBuffer, nBufferSize);
	if ((result > 0) && (pUnicodeBuffer != NULL))
		pUnicodeBuffer[result-1] = 0;

	return result;
}

int Unicode2Ansi(const wchar_t* pUnicode, char* pAnsiBuffer, int nBufferSize)
{
	if( (nBufferSize == 0) && (pAnsiBuffer != NULL) )
		return 0;

	int result = ::WideCharToMultiByte(CP_ACP, 0, pUnicode, -1, pAnsiBuffer, nBufferSize, NULL, NULL);
	if ((result > 0) && (pAnsiBuffer != NULL))
		pAnsiBuffer[result-1] = 0;

	return result;
}

int Ansi2Unicode(const char* pAnsi, wchar_t* pUnicodeBuffer, int nBufferSize)
{
	if( (nBufferSize == 0) && (pUnicodeBuffer != NULL) )
		return 0;

	int result = ::MultiByteToWideChar(CP_ACP, 0, pAnsi, -1, pUnicodeBuffer, nBufferSize);
	if ((result > 0) && (pUnicodeBuffer != NULL))
		pUnicodeBuffer[result-1] = 0;

	return result;
}

简单实用

CString strBuf;
int nSize = Unicode2UTF8(strBuf, NULL, 0);
char* szBuf = new char[nSize];
Unicode2UTF8(strBuf, szBuf, nSize);

以上就是C++实现字符格式相互转换的示例代码的详细内容,更多关于C++字符格式互换的资料请关注其它相关文章!

原文地址:https://blog.csdn.net/m0_37251750/article/details/108376157
 
标签: C++ 字符 格式 转换
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • Aurelius vs mORMot vs EntityDAC Delphi 的
    Aurelius vs mORMot vs EntityDAC   Delphi 的 ORM框架:http://www.tmssoftware.com/site/aurelius.asp#product-buy-onlinehttps://synopse.info/fossil/wiki/Synopse+OpenSourcehttps://www.devart.com/entitydac/download.htmlkbmMW  http://www.compo
    02-09
  • 【Ruby】Mac gem的一些坑
    前言自上一次升级MacOS系统后出现jekyll无法构建的问题,当时处理半天。谁知道最近又升级了MacOS,荒废博客多时,今天吝啬写了一篇准备发布,构建报错,问题重新。还是记录下,以防下次升级出问题。问题描述安装jekyll静态博客需要在Ruby环境下运行,于是参照
    02-09
  • iOS oc 调用 swift
    如股票oc要调用swift里面的代码 需要包含固定这个头文件项目名称 LiqunSwiftDemo-Swift.h         #ProjectName#-Swift.h固定的写法swift 目的 是取代oc 但是 不会完全取代 只是前端的替换LiqunSwiftDemo-Swift 点进去 可以看到 所有的swift代码 都产生
    02-09
  • objective-c NSTimer 定时器
    -(void)initTimer{//时间间隔NSTimeInterval timeInterval =3.0 ;//定时器repeats 表示是否需要重复,NO为只重复一次NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(mobileAnimation) userInfo:nil
    02-09
  • Objective-C  日记③ 字符串
    Objective-C 日记③ 字符串
    一、创建字符串、类方法   公式创建NSString  +(id) stringWithFormat:(NSString *) format,……;eg:  NSString *height;  height=[NSString stringWithFormat:@"高度是: %d 长度: %d",10,20];得到的字符串:“高度是: 10 长度: 20” 注意:  省
    02-09
  • Objective-C KVC机制
    Objective-C KVC机制http://blog.csdn.net/omegayy/article/details/7381301全部推翻重写一个版本,这是我在公司内做技术分享的文档总结,对结构、条理做了更清晰的调整。 1.    基本概念MODEL主要是英文文档里面经常出现的一些概念,讲解一下,方便英文
    02-09
  • objective-c 加号 减号 - +
    “加号代表static”是错误的说法,可能跟你那样表达的人其实意思是:“前置加号的方法相当于Java 里面的静态方法”。在Oc中,方法分为类方法和实例方法。前置加号(+)的方法为类方法,这类方法是可以直接用类名来调用的,它的作用主要是创建一个实例。有人把
    02-09
  • Objective-C  日记①
    Objective-C 日记①
    1、Xcode的.m扩展名表示文件含有Object-C代码,C以.c文件,C++以.cpp文件2、头文件声明:C使用:#include,O-C使用#import(当然你也可以使用#include) 3、输出方式:  C:printf("",参数);  O-C:NSLog(@"",参数); 4、布尔类型  C:bool 具有true
    02-09
  • ASP.NET MVC 操作AD 获取域服务器当前用户姓
    #region 根据当前登录域账号 获取AD用户姓名和所在OU目录/// summary/// 根据当前登录域账号 获取AD用户姓名和所在OU目录/// /summary/// param name="searchUser"要搜索的当前用户名/param/// param name="paths"out返回该用户所在OU目录/param/// param nam
    02-09
  • swift和OC - 拆分数组 和 拆分字符串
    1. 拆分数组 /// 根据 数组 截取 指定个数返回 多个数组的集合func splitArray( array: [Date], withSubSize subSize: Int) - [[Date]] {//数组将被拆分成指定长度数组的个数let count = array.count% subSize == 0 ? (array.count/ subSize) : (array.count
    02-08
点击排行