/*
Date: 10/03/19 12:49
Description: 求字符串長度函數實現的三種方法
*/
1 #include<stdio.h> 2 3 4 int strlen1(char *s); 5 int strlen2(char *s); 6 int strlen3(char *s); 7 8 9 int main(void) 10 { 11 char str[]="The function to test my length."; 12 printf("The length1 is:%d\n",strlen1(str)); 13 printf("The length2 is:%d\n",strlen2(str)); 14 printf("The length3 is:%d\n",strlen3(str)); 15 16 } 17 18 19 int strlen1(char *s)//設置計數器 20 { 21 int count=0; 22 while(*s!='\0') 23 { 24 s++; 25 count++; 26 } 27 return count; 28 } 29 int strlen2(char *s)//指針減指針的方法 30 { 31 char *p=s; 32 while(*p!='\0') 33 { 34 p++; 35 } 36 return p-s; 37 } 38 int strlen3(char *s)//利用函數遞歸的方法 39 { 40 if(*s=='\0') 41 return 0; 42 else 43 return 1+strlen3(s+1); 44 }
運行結果: