Three methods to achieve strlen()-(C language)

The strlen() function is derived from the library function <string.h>, which
is used to calculate the length of the
string , and the string needs to end with'\0'.
Strlen() will count the number of characters before the'\0'.

According to MSDN description

size_t strlen(const char* string);
size_t==unsigned int;

Return-unsigned integer.
Now provide three methods to achieve strlen()

Series Article Directory

1. Counter method
2. Recursion method
3. Pointer subtraction method



1. Counter method

We are counting the number of characters, we can set a variable, every time a character is found, the counter will increase by one.

int my_strlen(const char* arr)//计数器的方法
{
    
    
	assert(arr);
	int count = 0;
	while (*arr)//条件是*arr!='\0',但'\0'也是数字0,且条件是0为假,非0为真
	{
    
    
		count++;
		arr++;
	}
	return count;
}
int main(void)
{
    
    
	char arr[] = "abcdef";
	int len = my_strlen(arr);
	printf("len = %d\n", len);
	return 0;
}

Two, recursive method

Recursion can be calculated without creating variables.
Look at the code first

int my_strlen(const char* p)//递归法
{
    
    
	while (*p)
	{
    
    
		p++;
		my_strlen(p);
		return 1+my_strlen(p);//此时p已经是进入循环的p+1;
	}
	return 0;
	
}
int main(void)
{
    
    
	char arr[] = "abcde";
	int len = my_strlen(arr);
	printf("len = %d\n", len);
	return 0;
}

Pass the arr array name in, and use p to receive it. The same judgment condition, enter the loop, the pointer moves one byte to the right, get the address of the next character, enter the function again, and loop again

For example,
take the string as ab as an example and
Insert picture description here
finally dereference it to get'\0', and return 0. Then the upper level function returns 1 + the return value of the lower level function (0), and then returns to the upper level function, and its return value is 1+1+0. Exactly 2

Three, pointer minus pointer method

指针相减,得到的不是指针,而是两指针间的元素个数。


思路:我们找到首字符的指针,再找到‘\0'的指针,返回两指针相减的值。

See code

int my_strlen(const char* p)//指针相减法
{
    
    
	char* ret = p;
	while (*p)
	{
    
    
		p++;
	}
	return p - ret;

}
int main(void)
{
    
    
	char arr[] = "abcdef";
	int len = my_strlen(arr);
	printf("len = %d\n", len);
}

Because p will continue to move and the address pointed to by the pointer will change, first assign the first address to another pointer that will not change.
Insert picture description here
This picture is quite obvious.

The code can run, the compiler used is VS2019, remember to add the header file when running

Guess you like

Origin blog.csdn.net/weixin_52199109/article/details/112796848