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

来源:互联网 发布:淘宝crm系统架构 编辑:程序博客网 时间:2024/06/05 19:50
#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 stringPWSTR pEndOfStr = pWideCharStr + wcsnlen_s(pWideCharStr,cchLength)-1;wchar_t cCharT;//Repeat until we reach the center character of the stringwhile(pWideCharStr < pEndOfStr){//Save a character in a temporary variablecCharT = *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;}

原创粉丝点击