#include<stdio.h> #include<stdlib.h> #include<string.h>
int count_str (char*);
int main (int argc, char *argv[]) { char *str = NULL; str = (char *)malloc(sizeof(char) * 100);
printf("Please input the string you want to count:\n");
fgets(str, 100,stdin);
printf("The length of %s is mycount=%d,strlen=%d\n", str, count_str(str), strlen(str));
return 0; }
/* 不采用变量, 利用递归的方法 */ int count_str (char *string) { if(*string == '\0') { return 0; } else { return(1 + count_str(++string)); } }
gcc -o strlenstrlen.c ./strlen Please input the string you want to count: this is a The length of this is a is mycount=16,strlen=16
|
/* 采用指针变量,效率较低 */ int *count_str(char *str) { char *tmp = str;
while(*str != '\0') { str++; }
return src-tmp; }
|
/* 采用int变量, 效率相对比采用指针变量高很多 */ int count_str(char *str) { int len = 0;
for(; *str; ++len) { str++; }
return len; }
int count_str(char *str) { int len = 0;
for(; *str++ != '\0'; ) { len++; }
return len; }
|
/* 采用高效的办法 用unsigned long 变量 */
...待补充
阅读(848) | 评论(0) | 转发(0) |