码迷,mamicode.com
首页 > 其他好文 > 详细

求字符串长度的三种方法

时间:2015-10-28 01:41:21      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:c语言   函数   字符串   指针   递归   

1.指针
#include<stdio.h>

int strlen(char s[])
{
    int len=0;
	while(*s++!=‘\0‘)
	{
	      len++;
	}
	return len;
}
int main()
{
	char s[]="123456789";
	printf("%d\n",strlen(s));
	system("pause");
   return 0;
}


2.计数
#include<stdio.h>

int strlen(char s[])
{
    int i=0;
	int count=0;
	while(s[i++]!=‘\0‘)
	{
	    count++;
	}
	return count;
}
int main()
{
	char s[]="123456789";
	printf("%d\n",strlen(s));
	system("pause");
   return 0;
}

3.递归
#include<stdio.h>

int strlen(char s[])
{
	
   if(*s==‘\0‘)
	   return 0;
   else
	   return 1+strlen(s+1);
}
int main()
{
	char s[]="abcdef";
	printf("%d\n",strlen(s));
	system("pause");
   return 0;
}


求字符串长度的三种方法

标签:c语言   函数   字符串   指针   递归   

原文地址:http://760470897.blog.51cto.com/10696844/1706974

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!