#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;
}