de>#include<stdio.h>
#include<stdlib.h>
#define MAX_LEN 255
int my_strlen1(const char* str);
int my_strlen2(char* str);
int main()
{
char str1[MAX_LEN];
printf("Please input the string you want to strlen:\n");
fgets(str1,256,stdin);
printf("Length of %s is %d\n",str1,my_strlen1(str1));
char* str2="Hello,world!";
printf("Length of %s is %d\n",str2,my_strlen2(str2));
exit(EXIT_SUCCESS);
}
/*strlen,定义变量的写法*/
int my_strlen1(const char* str)
{
int len=0;
while(*(str+len)!='\0')
len++;
return len;
}
/*strlen,不用变量,递归的写法*/
int my_strlen2(char* str)
{
if(*str=='\0')
return 0;
else
return (1+my_strlen2(++str));
}de>
zj@zj:~/C_parm/string/own_str$ ./strlen
Please input the string you want to strlen:
hello,world!
Length of hello,world!
is 13
Length of Hello,world! is 12
*
*聪明的你也许发现那里有点不对劲了,对一个是12,一个是13!
其实strlen是不计算最后的字符串结束符'\0'的,那为什么有13呢?
看输出就知道了,有个换行符号,对就是你输入时的结束符,回车了哦*/de>