递归和非递归分别实现strlen

思路:strlren主要是字符串是以'\0'为结尾标识来计算字符串的长度,所以要实现自己去写strlen也要从这方面下手。

非递归思想:应用循环的思路,以'\0'为循环结束的标识,每循环一次计数加一。

注意:char str [ ] 种类字符串数组作为参数传入函数时会被隐式转换为指针。

 

 1 //非递归:
 2 #include <stdio.h>
 3 int Strlen(char* str)
 4 {
 5     int i = 0;
 6     while (*str != '\0')
 7     {
 8         ++str;
 9         ++i;
10     }
11     return i;
12 }
13 
14 int main()
15 {
16     char str[] = "abcdefghh";
17     printf("%d\n", Strlen(str));
18     return 0;
19 }

递归思想:每调运一次函数就加一,最后还是以'\0'为结束标志。

 1 //递归:
 2 #include<stdio.h>    
 3 int Strlen(char* str)
 4 {
 5     if (*str == '\0')
 6     {
 7         return 0;
 8     }
 9     else
10     {
11         return 1 + Strlen(++str);
12     }
13 }
14 
15 int main()
16 {
17     char str[] = "abcdefg";
18     printf("%d\n",Strlen(str));
19     return 0;
20 }

 

posted on 2019-01-31 22:07  The_Ocean  阅读(472)  评论(0编辑  收藏  举报

导航