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; 
     }
  • 相关阅读:
    INFO: InstallShield不同版本对中文字符串的支持程度
    Basic INFO: InstallShield 2012安装过程
    [Android] 打印Log的行号、函数、类名
    gridgian 网格计算
    Activity及Dialog的全透明
    设计工具
    ps 多图层扣图
    spket js ide
    a 的样式
    js开发规范
  • 原文地址:https://www.cnblogs.com/wanghao-boke/p/11030141.html
Copyright © 2011-2022 走看看