一个字符旋转的算法本例程用于对字符串按一定要求进行旋转,并自动适应ansi或者Unicode编码,可以中英文混排的字串
举例:pBuf=_T("abc中国人民解放军")
调用:ShiftString(pBuf,4)
结果:国人民解放军abc中
//计算n个字符需要的空间(n个字符需要的空间根据根据编码不同)
//nChar如果为-1,返回整个字串字节长度,否则返回n个字符长度
//本例程用于处理ansi及其Unicode
inline int GetBytes(LPTSTR pBuf,int nChar=-1)
{
#ifdef _UNICODE
int n=0;
if(nChar<0)
{
wchar_t* p=pBuf;
while(*p)
{
n++;
p++;
}
}
else
n=nChar;
return n*sizeof(wchar_t);
#else
int nBytes=0;
int n=0;//当前字符数
int nMax=2147483647;//最大为2G的空间
if(nChar<0)
{
nChar=nMax;
nBytes=-1;
}
while(pBuf[nBytes] && n<nChar)
{
if(pBuf[nBytes]<0)
nBytes+=2;
else
nBytes++;
n++;
}
return nBytes;
#endif
}
void ShiftString(LPTSTR pBuf,int nChar)
{
int nBytes=GetBytes(pBuf,nChar);
int nLen=GetBytes(pBuf);
char* pTemp=new char[nBytes];//不需要设置0
int nTail=nLen-nBytes;
memmove(LPVOID(pTemp),LPVOID(pBuf),nBytes);
memmove(LPVOID(pBuf),LPVOID((char*)pBuf+nBytes),nTail);
memmove(LPVOID((char*)pBuf+nTail),LPVOID(pTemp),nBytes);
delete[]pTemp;
}
void CMyTestPrj2View::OnTest4CharTurn()
{
// TODO: 在此添加命令处理程序代码
TCHAR pBuf[]=_T("abc中国人民解放军");
ShiftString(pBuf,4);
//pBuf==>国人民解放军abc中
}