C语言:三种方法模拟实现strlen函数

在模拟实现strlen函数之前,我们首先来看下strlen函数的定义即功能:strlen所作的仅仅是一个计数器的工作,它从内存的某个位置(可以是字符串开头,中间某个位置,甚至是某个不确定的内存区域)开始扫描,直到碰到第一个字符串结束符’\0’为止,然后返回计数器值(长度不包含’\0’)。即strlen函数计算的是不算结束标志符’\0’在内的字符串的长度。

了解了strlen函数的定义即功能,下面我们就来看看它的模拟实现方法:

第一种方法,使用计数器的方法。即当字符数组的指针没有指向’\0’即字符串结束标志时,也就是当字符串没有结束时,让字符数组的指针一直往后移动,同时移动一位,count的值加1一次,最后函数返回count的值,即返回了字符串的长度。
在具体实现代码时要注意两点:
1、我们定义的指针不能为空,所以要使用assert进行断言。
2、因为是判断字符串长度,所以字符串是不变的,所以用const修饰,使其更加安全。
下面是具体实现代码:

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>


int my_strlen(const char*str)
{
    assert(str != NULL);
    int count = 0;//计数器
    while (*str != '\0')
    {
        count++;
        str++;
    }
    return count;
}
int main()
{
    char string[] = "abcdef";//应将字符串放入一个字符型数组中
    int ret = 0;
    ret = my_strlen(string);
    printf("字符串长度为:%d\n", ret);
    system("pause");
    return 0;
}

第二种方法,采用递归的方法。即当字符串为0即一开始就找到了’\0’,那么函数返回0,否则返回1+参数为字符串指针加1再调用此函数。同时此方法也要注意断言和const修饰两点。下面是具体实现代码:

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

int my_strlen(const char *str)
{
    assert(str != NULL);
    if (*str == '\0')
    {
        return 0;
    }
    else
    {
        return 1 + strlen(str + 1);
    }

}
int main()
{
    char string[] = "abcdefjikjas";
    int ret = 0;
    ret = my_strlen(string);
    printf("字符串的长度为:%d\n", ret);
    system("pause");
    return 0;
}

第三种方法,采用指针-指针的方法。我们知道,指针-指针的结果是返回之间元素的个数。所以我们可以定义一个指针变量将字符串首元素的地址存放起来, 然后当字符串指针没有找到’\0’时让指针后移,最后将字符串指针-刚才定义的首元素地址的指针,得到的就是字符串的个数。具体实现代码时也要注意assert断言和const修饰。下面是具体实现代码:

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
/*基本思想:指针-指针的结果是中间元素的个数 定义一个指针存放字符串起始的位置,然后当字符串指针没到'\0'的位置时
           让字符串指针一直往后移,直到遇到'\0',最后用字符串指针减去起始位置的指针,就是中间的元素个数*/

int my_strlen(const char*str)//因为字符串是不用变的,所以用const
{
    assert(str != NULL);
    const char*start = str;//用一个指针来存放起始指针的位置 要用const修饰,因为str就是一个const修饰的变量
    while (*str != '\0')
    {
        str++;
    }
    return str - start;
}
int main()
{
    char string[] = "abcdefhijklmn";
    int ret = 0;
    ret = my_strlen(string);
    printf("字符串长度为:%d\n", ret);
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/windyj809/article/details/80037006