zoukankan      html  css  js  c++  java
  • isspace 对含有中文 的字符串进行检查的时候表现不正常!?

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    
     
    
    //删除右边连续的空格,
    char* rtrim(char *pstr)
    {
        char *p = pstr;
    
        int len = strlen(pstr);
        p += len - 1;
        
        for(; isspace(*p) && len > 0; p--,len--)
        {
            *p = ''; //截断
        }
    
        return pstr;
    }
    
    int main()
    {
        char text[] = {"D:\我的文档  "};
        printf("text:%s, length:%d
    ",text,strlen(text));
    
        char *p = rtrim(text);
    
        printf("text:%s, length:%d
    ",p,strlen(p));
    
        return 0;
    }

    输出结果: (为什么中文[文档]两字会输出乱码?)
    ---------------------------------------

    text:D:我的文档  , length:13
    text:D:我的? length:8


    检查了半天,估计是isspace()的问题,不使用isspace(), 改写:

    for(; (*p == ' ' || *p == ' ' || *p == ' ' || *p == ' ') && len > 0; p--,len--)
     {
            *p = ''; //截断
    }

    再测试,就正常了。

    输出结果: 
    ---------------------------------------
    text:D:我的文档  , length:13
    text:D:我的文档, length:11

    续:

    几天之后又意外发现,在处理 '字'开头的中文时,也会出现乱码。

    看来以后处理中文字符串的时候,不能用isspace()函数了,太危险了。

  • 相关阅读:
    python框架之Flask(4)-上下文管理
    python框架之Flask(3)-Blueprint(蓝图)
    python框架之Flask(2)-路由和视图&Session
    python框架之Flask(1)-Flask初使用
    python中使用redis
    python之以字符串形式导入模块
    学习进度
    学习进度
    毕设进度
    毕设进度
  • 原文地址:https://www.cnblogs.com/personnel/p/4584815.html
Copyright © 2011-2022 走看看