一只程序猿的养成日记 第一章 第十四节 递归和非递归分别实现strlen

来源:互联网 发布:守望先锋设置优化 编辑:程序博客网 时间:2024/06/04 18:05

递归和非递归分别实现strlen 

迭代实现strlen 

 

#include<stdio.h> 

#include<windows.h>  

#include<assert.h>  

  

int my_strlen(const char* str)  

{  

    int count = 0;  

    assert( str);  

    while( *str)  

    {  

        count++;  

        str++;  

    }  

    return count;  

}  

  

int main()  

{    

    printf("len = %d\n",my_strlen("abcdef"));   

    system("pause");  

    return 0;  

}

 

递归实现strlen 

 

#include<stdio.h> 

#include<windows.h>  

#include<assert.h>  

  

int my_strlen(const char* str)  

{  

    assert(str != NULL);  

    if(*str)  

        return 1+my_strlen(str+1);  

    else  

        return 0;  

}  

 

int main()  

{

printf("len= %d\n",my_strlen("abcdef"));  

    system("pause");  

    return 0;  


阅读全文
0 0
原创粉丝点击