zoukankan      html  css  js  c++  java
  • C语言 字符串操作两头堵模型

    //字符串操作两头堵模型练习
    
    #define _CRT_SECURE_NO_WARNINGS
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    //去除字符串中的空格
    //const char *pin的解释:const char *pin是用来限制指针pin指向的数据是个常量,不允许修改,
    //但是并不限制实参指针指向的数据也必须是一个常量
    //这是为了防止传过来的参数pin所指向的数据不可以修改,但是却在函数里做了修改,导致程序报错,这是一种标准的写法
    int removespace(const char *pin,char *pout){
        int ERRO_MSG = 0;
        //验证传入参数是否为空
        if (pin == NULL || pout==NULL)
        {
            ERRO_MSG = 1;
            printf("pin == NULL || pout==NULL erro msg key:%d
    ", ERRO_MSG);
            return ERRO_MSG;
        }
        //两头堵模型就是要准备两个辅助指针,一个在头部,一个在尾部
        int i = 0, j = 0;
        //定义不是空格的字符的个数
        int index = 0;
        //不清楚具体循环次数,一般使用while或者do...while...
        //i从头开始
        //注意:pin[i]==" "这么些是错误的," "是字符串(2个字符,''也算一个),pin[1]是一个char类型
        while (pin[i] != ''&&pin[i]==' '){
            i++;
        }
        j = strlen(pin);
        //j从尾部开始
        while (pin[j] != ''&&pin[i] ==' '){
            j--;
        }
        index = j - i + 1;   //例如  "ab"  a的位置是0,b的位置是1,则1-0=1,实际字符个数是2
        //拷贝字符串
        strncpy(pout, pin + i, index);
        return ERRO_MSG;
    }
    
    void main(){
        char buf2[] = "       adfr    ";
        //这里两种分配字符串的方式
        //方式一(推荐)
        char buf[20] = { 0 };
        //方式二(第二种方式,并没有初始化分配的内存,因此需要在函数中将p1指向的内存的数据初始化为'')
        char *p1 =(char *)malloc(sizeof(char)* 10);
        //初始化p1
        memset(p1, 0, sizeof(p1));
        //注意:memset()相比于char buf[20] = { 0 };这种方式要消耗更多的资源
        removespace(buf2, buf);
        //malloc分配的内存必须回收
        free(p1);
        printf("%s
    ", buf);
        system("pause");
    }

     

    //字符串操作两头堵模型练习
    
    #define _CRT_SECURE_NO_WARNINGS
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    //字符串反转
    int reversestr(const char *pin,char *pout){//pin是形参,一个临时变量,pin的值发生变化,不会影响实参p的值
        //定义返回key
        int ERRO_MSG = 0;
        //形参非空校验
        if (pin == NULL || pout==NULL)
        {
            ERRO_MSG = 1;
            printf("pin == NULL || pout==NULL erro msg key:%d
    ", ERRO_MSG);
            return ERRO_MSG;
        }
        //两头堵模型
        int i = 0, j = strlen(pin)-1;//p[5]是''
        while (j >= i){
            //将字符一个个填入字符数组里
            *pout++ = pin[j--];
        }
        return ERRO_MSG;
    }
    
    void main(){
        char *p = "abcde";
        char strarr[10] = { 0 };
        reversestr(p, strarr);
        printf("%s
    ", strarr);
        system("pause");
    }

  • 相关阅读:
    黄聪:Jquerry如何深拷贝对象
    黄聪:IIS7下wordpress上传大文件(30M以上)提示404页面失败的解决方法
    黄聪:Vue的list根据index序号删除元素
    php防止视频资源被下载
    前端Jquery-Ajax跨域请求,并携带cookie
    完美验证码识别系统,验证码插件使用帮助文档
    C#截图操作(几种截图方法)
    最全各种系统版本的XPosed框架资料下载整理
    wp.editor.initialize 配置案例
    黄聪:wordpress登录后台后load-scripts.php载入缓慢
  • 原文地址:https://www.cnblogs.com/zhanggaofeng/p/5305389.html
Copyright © 2011-2022 走看看