Three simulation implementation methods of library function strlen


1. Understanding the library function strlen

We can learn about the library function strlen from the following link: The library function strlen is a function to find the length of a string
https://legacy.cplusplus.com/reference/cstring/ strlen/?kw=strlen

size_t strlen ( const char * str )

Note
The string uses '\0' as the end mark. The library function strlen returns the number of characters that appear before '\0' in the string but does not include ' \0', there is a '\0' hidden at the end of the double quotation mark ("")

The string pointed to by the parameter must end with ‘\0’

The return value of the function is size_t, which is unsigned

2. Use of library function strlen

#include <stdio.h>
#include <string.h>//使用库函数strlen需要的头文件
int main()
{
    
    
	char arr[] = "abcdef";
	int ret = strlen(arr);
	printf("%d\n", ret);
	return 0;
}

operation result:
Insert image description here

#include <stdio.h>
#include <string.h>
int main()
{
    
    
	char arr[] = {
    
     'a','b','c','d' };//没有字符'\0'
	int ret = strlen(arr);
	printf("%d\n", ret);
	return 0;
}

Because it will stop when it reads '\0', but there is no '\0' in the program, so it gets a random value.
Insert image description here

int main()
{
    
    
	char arr1[] = "abcd";
	char arr2[] = "abcdef";
	if (strlen(arr1) - strlen(arr2) > 0)
		printf(">=\n");
	else
		printf("<\n");
	return 0;
}

Because the return value of the library function strlen is suze_t (unsigned integer), it is greater than 0
Insert image description here

3. Three simulation implementation methods of library function strlen

1. Use counter to implement

#include <stdio.h>
int my_strlen(const char* str)
{
    
    
	int count = 0;//设置计数器
	while (*str!='\0')//对指针进行解引用找到那个值,若那个值不等于'\0'则向后依次找
	{
    
                     //直到找到'\0',结束循环
		count++;//每次找到一个值,计算器++
		str++;
	}
	return count;//循环结束返回计数器的值
}
int main()
{
    
    
	char str[] = "abcdef";
	int len = my_strlen(str);
	printf("%d\n", len);
	return 0;
}

Insert image description here

2. Use function recursion

#include <stdio.h>
int my_strlen(const char* str)//每次递归都会使指向首元素的指针加1,直到遇到'\0'递归结束
{
    
                                 
	if (*str == '\0')
		return 0;
	else
		return 1 + my_strlen(str + 1);//递归每进行一次返回值就加1
}
int main()
{
    
    
	char str[] = "abcdef";
	int len = my_strlen(str);
	printf("%d\n", len);
	return 0;
}

Insert image description here

3. Pointer-pointer method

#include <stdio.h>
int my_strlen(char* s)
{
    
    
	char* p = s;//把函数传来的值赋给指针p
	while (*p != '\0')//对指针p进行解引用,如果不为'\0',则依次向后找,直到找到'\0'结束循环
	{
    
    
		p++;
	}
	return p - s;//对指针相加减计算的是中间元素的个数
}
int main()
{
    
    
	char str[] = "abcdef";
	int len = my_strlen(str);
	printf("%d\n", len);
	return 0;
}

Insert image description here

Guess you like

Origin blog.csdn.net/2301_78373304/article/details/133031441