在计算机中,一个汉字用无法用1个字节来表示
#include<stdio.h> int main() {char buf[256] = "你好";int len = 0;while(buf[len++]);len--;printf("%d\n",len);// 4一个汉字两个字节 //printf("%p\n",buf);return 0; }
在windows下采用gbk字符编码,一个汉字采用两个字节表示,所以windows环境下对于汉字的逆置就需要考虑两个字节的整体交换
#include<stdio.h>int main() {char buf[256] = "你好世界";int len = 0;while(buf[len++]);len--;printf("%d\n",len);// 4一个汉字两个字节 //逆置int min = 0;int max = len - 1;while(min < max){char temp = buf[min];buf[min] = buf[max - 1];buf[max - 1] = temp;temp = buf[min + 1];buf[min + 1] = buf[max];buf[max] = temp;min += 2;max -= 2;} printf("buf = %s",buf);return 0; }
而在linux环境下,采用的utf-8的汉字字符编码,所以逆置就需要考虑三个字符的整体交换
#include<stdio.h>int main() {char buf[256] = "你好世界";int len = 0;while(buf[len++]);len--;printf("%d\n",len);// 4一个汉字两个字节 //逆置int min = 0;int max = len - 1;while(min < max){char temp = buf[min];buf[min] = buf[max - 2];buf[max - 2] = temp;temp = buf[min + 1];buf[min + 1] = buf[max-1];buf[max-1] = temp;temp = buf[min + 2];buf[min + 2] = buf[max];buf[max] = temp;min += 3;max -= 3;} printf("buf = %s\n",buf);return 0; }