C find the length of a string

1. Topic

Recursive and non-recursive implementations of strlen respectively

2. Program code

#define _CRT_SECURE_NO_WARNINGS 1

#include <stdio.h>
#include <Windows.h>

int my_strlen1(char *string)//非递归方式求字符串长度
{
    int count = 0;

    while (*(string++))
    {
        count++;
    }
    return count;
}

int my_strlen2(char *string)//递归方式求字符串长度
{
    if (*string == '\0')
    {
        return 0;
    }
    return 1 + my_strlen2(string + 1);
}

int main()
{
    char string[] = "abcdefg";

    printf("%d\n", my_strlen1(string));
    printf("%d\n", my_strlen2(string));

    system("pause");
    return 0;
}

3. Execution results

write picture description here

Guess you like

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