逆转中文字符串-->逆转字符串
要显示中文必须使用unsigned char型,如果使用char 就装不下了。
然后要明白一个unsigned char 其实只是装了一个中文字符的一半。打印的时候如果只打印一个unsigned
char有可能什么都看不到。所以逆转的时候要把两个unsigned char看成一个整体来交换。代码如下:
#include < iostream >
using namespace std;
int main( void )
{
unsigned char * string1 = new unsigned char [ 20 ];
unsigned char * b , * p;
b = p = string1;
while ( * p)
{
p ++ ;
}
p = p - 2 ;
while (p > b)
{
swap( * p, * b);
p ++ ;
b ++ ;
swap( * p, * b);
p = p - 3 ; // 转到下一个中文字符的第一个unsigned char
b ++ ;
}
cout << string1;
return 0 ;
}
其中的while(*p){p++;}p-=2;也可以用p = &string1[strlen(string1)-2]代替。。
char * Reverse( const char * str)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBloc
kStart.gif) ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/
ContractedBlock.gif) … {
if (str == NULL)
throw " Null point " ;
int size = strlen(str);
if (size == 0 )
return “” ;
const char * p = str;
char * newStr = new char [size + 1 ];
char * temp = newStr;
while ( * p ++ );
p = p - 2 ; // 到达末尾的非’/0’字符
int i = 0 ;
while (p != str && i < size )
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
lockStart.gif) ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicato
rs/ContractedSubBlock.gif) … {
unsigned char * x = (unsigned char * )p;
if ( * x > 0x7f )
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
lockStart.gif) ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicato
rs/ContractedSubBlock.gif) … {
// DBCS
- temp ++ = *-- p;
- temp ++ = *++ p;
p = p - 2 ;
i += 2 ;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
lockEnd.gif) }
else
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
lockStart.gif) ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicato
rs/ContractedSubBlock.gif) … {
// SBCS
- temp ++ = * p -- ;
i ++ ;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
lockEnd.gif) }
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
lockEnd.gif) }
if (i < size)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
lockStart.gif) ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicato
rs/ContractedSubBlock.gif) … {
- temp ++ = * str;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
lockEnd.gif) }
- temp = ’ /0 ’ ;
return newStr;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBloc
kEnd.gif) }
同时发现一个CSDN插入代码的bug。当插入代码中出现‘/0’的时候就会截断。所以我只能用’//0’代替了。
当字符串中有DBCS双字节字符时,使用同时转换两个。当有SBCS单字节字符串时转换一个。
(但是有些DBCS字符是占用两个以上空间的。但是没有考虑)这只是个简单的转换。