递归求解字符串长度

来源:互联网 发布:六味地黄丸 知乎 编辑:程序博客网 时间:2024/05/18 00:17

今天看了个有意思的程序,用递归就能求解字符串长度。然后自己敲敲代码试试看。

[cpp] view plaincopyprint?
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <assert.h>  
  4.   
  5. #define MAXSIZE 50  
  6.   
  7. int mystrlen(const char *strDest)  
  8. {  
  9.     assert(NULL != strDest);        //assert宏入口检测  
  10.     if('\0' == *strDest)            //字符串结束  
  11.         return 0;  
  12.     else  
  13.         return (1 + mystrlen(++strDest));       //递归求解字符串长度  
  14. }  
  15.   
  16. int main(void)  
  17. {  
  18.     char *ch;  
  19.     int len;  
  20.       
  21.     ch = (char*)malloc(sizeof(char)*MAXSIZE);  
  22.   
  23.     printf("Input a string:");  
  24.     scanf("%s", ch);  
  25.     len = mystrlen(ch);  
  26.     printf("%d", len);  
  27.     printf("\n");  
  28.     return 0;  
  29. }  


同时学到了用调试宏做入口检测的方法,使程序更加完善。

0 0
原创粉丝点击