zoukankan      html  css  js  c++  java
  • c语言中判断字符串的长度,利用数组和利用指针

    c语言中判断字符串的长度,利用数组和利用指针。

    1、利用数组。

    #include <stdio.h>
    
    int len(const char x[])
    {
        int len = 0;
        while(x[len])
            len++;
        return len;    
    } 
    
    int main(void)
    {
        char str[128];
        printf("str: "); scanf("%s", str);
        
        printf("length:  %d
    ", len(str));
        return 0;
    }

    2、利用指针

    #include <stdio.h>
    
    int len2(char *x)  //利用指针作为形参,指针x指向传入的数组的第一个元素,其行为和数组str一样,x++指针依次向后推移,知道*x=0, 测试循环体执行了字符个数的次数 
    {
        int len = 0;
        while(*x++) //指针的推移控制循环变量,直到*x为null, 
            len++;  //循环体记录字符个数 
        return len;
    }
    
    int main(void)
    {
        char str[128];
        printf("str:  "); scanf("%s", str);
        printf("length: %d
    ", len2(str));
        return 0;
    }

    #include <stdio.h>
    
    int leng(const char *x)
    {
        int len = 0;
        while(*x++)
            len++;
        return len;
    }
    
    int main(void)
    {
        char *str = "abcde";  //利用指针实现数组 
        printf("length:  %d
    ", leng(str));
        return 0;
    }

  • 相关阅读:
    通过索引优化sql
    索引概述
    Spring整合Mybatis
    Mybatis逆向工程
    Mybatis级联
    Mybatis动态语句
    Mybatis—curd
    (转)最大似然估计&贝叶斯估计
    筛法求质——poj2262&2909
    (转)poj1182食物链
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14830468.html
Copyright © 2011-2022 走看看