Detailed explanation of strlen function in C language

1. Introduction to strlen function

1. Function prototype

size_t strlen ( const char * str );

2. Precautions

① The string ends with '\0', and the strlen function returns the number of characters that appear before '\0' in the string (excluding '\0'); for example
 :

#include <stdio.h>
#include <string.h>

int main()
{
    
    
	char arr[] = "abcdefg";// "abcdefg\0"
	int num = strlen(arr);
	printf("%d\n", num);
	return 0;
}

Output result:
insert image description here

②The string pointed to by the parameter must end with '\0';
  for example, the definition of the string is as follows: char arr[]={'a','b','c','d',};
  the output result will be a random value, because it is unknown where '\0' is in this character array.

③ The return value of the function is size_t, which is an unsigned number.
  This item is the easiest to overlook and is an error-prone point.
example:

int main()
{
    
    
	const char*str1 = "abcdefg";
	const char*str2 = "cdef";
	if(strlen(str2)-strlen(str1)>0)
	{
    
    
		printf("str2>str1\n");
	}
	else
	{
    
    
		printf("srt1>str2\n");
	}
	return 0;
}

insert image description here
  The reason why such a result occurs is that the length of str1 is 7, and the length of str2 is 4. In the if judgment condition, the length of str2 minus the length of str1 is -3, but the return value type of the strlen function is unsigned type, so it will be converted into a number greater than 0, and then the result of str2 > str1 will appear.

2.Strlen function simulation implementation

1. Counter method

int my_strlen(char* str)
{
    
    
	int count = 0;
	while (*str++)
	{
    
    
		count++;
	}
	return count;
}

2. Recursive implementation

int my_strlen(char* str)
{
    
    
	if (*str == '\0')
	{
    
    
		return 0;
	}
	else
		return my_strlen(str+1) + 1;
}

3. Pointer-pointer implementation

int my_strlen(char* str)
{
    
    
	char* s = str;
	while (*s)
	{
    
    
		s++;
	}
	return s - str;
}

Guess you like

Origin blog.csdn.net/weixin_47648037/article/details/126806971