zoukankan      html  css  js  c++  java
  • 汉字逆置

    在计算机中,一个汉字用无法用1个字节来表示

    #include<stdio.h>
    int main()
    {
        char buf[256] = "你好";
        int len = 0;
        while(buf[len++]);
        len--;
        printf("%d
    ",len);// 4一个汉字两个字节 
        //printf("%p
    ",buf);
        return 0; 
     }

    在windows下采用gbk字符编码,一个汉字采用两个字节表示,所以windows环境下对于汉字的逆置就需要考虑两个字节的整体交换

    #include<stdio.h>
    
    int main()
    {
        char buf[256] = "你好世界";
        int len = 0;
        while(buf[len++]);
        len--;
        printf("%d
    ",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
    ",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
    ",buf);
        return 0; 
     }
  • 相关阅读:
    集合
    3/11
    字典
    3/10
    字符串之不常用方法
    字符串的索引和切片
    数据类型的转化
    Markdown在线编辑器
    3/9
    Django:RestFramework之-------渲染器
  • 原文地址:https://www.cnblogs.com/wanghao-boke/p/11030141.html
Copyright © 2011-2022 走看看