c++ 字符串反转方法 UNICODE 和 ANSI 版本

#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
#include <Windows.h>
#include <iostream>

#define chmalloc (TCHAR*)malloc(nCharacter*sizeof(TCHAR))

static BOOL StringReverseW(PWSTR pWideCharStr,DWORD cchLength)
{
	//Get a pointer to the last character in the string
	PWSTR pEndOfStr = pWideCharStr + wcsnlen_s(pWideCharStr,cchLength)-1;
	wchar_t cCharT;
	//Repeat until we reach the center character of the string
	while(pWideCharStr < pEndOfStr)
	{
		//Save a character in a temporary variable
		cCharT = *pWideCharStr;
		*pWideCharStr = *pEndOfStr;
		*pEndOfStr = cCharT;
		pWideCharStr++;
		pEndOfStr--;
	}
	return TRUE;
}

static BOOL StringReverseA(PSTR pMultiByteStr,DWORD cchLength)
{
	PWSTR pWideCharStr;
	int nLenWideCharStr;
	BOOL fOK = FALSE;
	//Calculate the number of characters needed 
	//to hold the wide-character version of the string.
	nLenWideCharStr = MultiByteToWideChar(CP_ACP,0,pMultiByteStr,cchLength,NULL,0);

	//从进程默认的堆中分配一定的内存来存放适当的宽字符字符串
	//不要忘记MultiByteToWideChar 返回的是字符的个数,不是字节数,所以要将字符个数再乘以sizeof(wchar_t)
	pWideCharStr = (PWSTR)HeapAlloc(GetProcessHeap(),0,nLenWideCharStr*sizeof(wchar_t));
	if(pWideCharStr == NULL)
		return(fOK);
	//将多字节字符串转换成宽字符字符串
	MultiByteToWideChar(CP_ACP,0,pMultiByteStr,cchLength,pWideCharStr,nLenWideCharStr);
	//调用宽字符版本的函数来实现实际的工作
	fOK = StringReverseW(pWideCharStr,cchLength);
	if (fOK)
	{
		//Convert the wide-character string back to a multibyte string.
		WideCharToMultiByte(CP_ACP,0,pWideCharStr,cchLength,pMultiByteStr,
			(int)strlen(pMultiByteStr),NULL,NULL);
	}
	//Free the memory containg the wide-character string.
	HeapFree(GetProcessHeap(),0,pWideCharStr);
	return(fOK);

}

int _tmain(int argc, _TCHAR* argv[])
{
	TCHAR strWChar[30] = TEXT("abcdefghigklmn");
	std::wcout<<strWChar<<std::endl;
	StringReverseW(strWChar,_countof(strWChar));
	std::wcout<<strWChar<<std::endl;
	char strChar[20] = "abcdef";
	std::cout<<strChar<<std::endl;
	StringReverseA(strChar,_countof(strChar));
	std::cout<<strChar<<std::endl;
	system("pause");
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值