Talking about strlen() realization

strlen string length

  1. A string, strlen ends with'\0', and the strlen function returns the number of characters appearing before'\0' in the string.
    Distinguish between strlen and sizeof
      1. strlen is a function, and sizeof is a keyword.
      2. strlen is used to calculate the length of the string and \0 is not calculated in the length.
      3. sizeof is the number of bytes occupied by the calculation type, and the size of the memory occupied by the string is calculated, and \0 is calculated.
      4. sizeof can not only calculate the number of bytes occupied by the string, but also the number of bytes occupied by the type.

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

  3. In the process of passing pointers, assign values, pass parameters, permissions cannot be enlarged, only reduced

  4. Function realization
    method one

     size_t my_strlen(const char* str)//这块要是没有const p2就传不过来
     {
     	size_t len = 0;
     	while (*str)//*str != '\0'
     	{
     		len++;
     		str++;
     	}
     	return len;
     }
    

      In the function definition, what is passed is a const type variable, otherwise a const char* p2 = "hello"; is declared. When p2 is called, if there is no const, it cannot be passed, because the pointer is assigned during the transfer process , Passing parameters, permissions cannot be enlarged, only reduced, which violates the third principle, on the contrary, the function has const, define a char * p1 = "hello";, without const, it can also be passed.
    Method Two

     size_t my_strlen(const char* str)
     {
     	const char* tail = str;
     	while (*tail++);
     	return tail - str - 1;
     }
    

      In the function body, a char type pointer tail is defined to record the first address of the string, and then tail loops, as long as it is not'\0', tail++ is added directly; it means that the while statement body is an empty statement , Because while has been added to'\0' before stopping, the while statement is executed, the position pointed to by the tail pointer is'\0', the return value must be subtracted by 1, and the two pointers are subtracted to obtain x pointer types The number, which is the length of the string.
    Method Three

     size_t my_strlen(const char* str)
     {
     	const char* tail = str;
     	while (*tail)
     	{
     	tail++;
     	}
     	return tail - str;
     }
    

      Method three is an expanded understanding of method two, which is easier to understand than method two.

Guess you like

Origin blog.csdn.net/weixin_43580319/article/details/112140764