How to find the length of a string without using the strlen function

I came across some interesting posts today, one of which was to find the length of a string without using the strlen function.

My first thought was to use a variable as an accumulator and then loop over the string.

#include <stdio.h>
int str(char *x)
{
	int l=0;
	while (*x++!=0)
	{
		l+=1;
	}
	return l;
}
int main()
{
	char x[100];
	printf("请输入一个字符串:\n");
	scanf("%s",x);
	printf("该字符串的长度为:%d\n",str(x));
	return 0;
}

When I saw that post, it said that it can be implemented using recursion, I immediately clicked

#include <stdio.h>
int str(char *x)
{
	if(*x++ =='\0') return 0;
	else return ("%d",1+str(x++));
}
int main()
{
	char x[100];
	printf("请输入一个字符串:\n");
	scanf("%s",x);
	printf("长度为:%d\n",str(x));
	return 0;
}


Run it, it really works!

I think this recursion is better than the previous one, at least in terms of the amount of code. There are many methods in that post, but I have never seen them. Never thought about it,

http://bbs.csdn.net/topics/240070349 This is the link to that post. This post is relatively old, but I feel that it is still quite useful to me. At least to me, it is a Nice ideas.



Guess you like

Origin blog.csdn.net/qq_31849705/article/details/52122975