在字符逆序是我们实际开发和面试中常见的问题,常见到的是ASCII字符串逆序,ASCII编程字符串逆序比较简单,一个字母、数字或者符号只占用一个字节,因此逆序也相对较容易。然而汉字太多一个字节不够编码,因此一个汉字占用两个字节,其采用GBK编码方法。同时GBK为了兼容ASCII编码,规定汉字的每一个字节第八位为1(ASCII编码方式共用了七位)。如果知道了上述这些也就比较容易写出含有中文字符串的逆序。
程序:
#include<iostream>
#include<string.h>
using namespace std;
char *stringReverse(char *src)
{
if(src==NULL)
{
return NULL;
}
int len=strlen(src);
char *dest=new char[len+1];
char *end=src+len-1;
char *tmp=NULL;
char *start=dest;
while(end>=src)
{
if(*end&0x80)//判断第八位是否为1
{
tmp=end;
end--;
*start=*end;
start++;
*start=*tmp;
}
else
{
*start=*end;
}
end--;
start++;
}
if(end==src)
{
*start=*end;
}
dest[len]=0;
return dest;
}
int main(int argc,char *argv[])
{
char *p="hello world";
char *q="1中国a";
char *t="中国 亚洲";
cout<<stringReverse(p)<<endl;
cout<<stringReverse(stringReverse(p))<<endl;
cout<<stringReverse(q)<<endl;
cout<<stringReverse(stringReverse(q))<<endl;
cout<<stringReverse(t)<<endl;
cout<<stringReverse(stringReverse(t))<<endl;
system("pause");
}
测试结果