C language simulation realizes strlen() of standard library function

strlen()

strlen所作的仅仅是一个计数器的工作,它从内存的某个位置
(It can be the beginning of the string, somewhere in the middle, or even an indeterminate memory area)
开始扫描,直到碰到第一个字符串结束符'\0'为止,然后返回计数器值(长度不包含'\0')。

Note:

In order to facilitate reading, the header file and the main function are given at the beginning of the article, and only the content of the function is written later, which is convenient for readers to read

#define _CRT_SECURE_NO_WARNINGS 
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char arr[] = "asdfdsaf";
    printf("%d", my_strlen(arr));
    system("pause");
    return 0;
}

Method 1: The counter method implements strlen()

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

}

Method 2: Recursive implementation of strlen()

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

Method 3: Subtraction of pointers to implement strlen()

int my_strlen(char *arr)
{
    char * str1 = arr;
    while (*arr != 0)
        arr++;
    return arr - str1;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325594775&siteId=291194637