strlen的三种实现方式

2021年09月15日 阅读数:1
这篇文章主要向大家介绍strlen的三种实现方式,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

#include <stdio.h>数组

#include <stdlib.h>ide


//实现strlenspa


int my_strlen1(char str[])//数组指针

{递归

                 int count = 0;it

                 int i = 0;io

                 while (str [i] != '\0')class

                {im

                                count++;di

                                i++;

                }

                 return count;

}


int my_strlen2(char *str)//指针

{

                 int i = 0;

                 while (*str )

                {

                                i++;

                                 str++;

                }

                 return i;

}


int my_strlen3(char *str)//递归

{

                 int i = 0;

                 if (*str == '\0')

                {

                                 return 1;

                }

                 return 1 + my_strlen3(str + 1);

}


int main()

{

                 char str[] = "abcdef" ;

                 int ret = my_strlen1(str);

                printf( "%s的长度为%d\n" , str, ret);

                 int ret2 = my_strlen2(str);

                printf( "%s的长度为%d\n" , str, ret2);

                 int ret3 = my_strlen3(str);

                printf( "%s的长度为%d\n" , str, ret3);

                system( "pause");

                 return 0;