How to find length of a string without strlen (string.h) and loop in C?

In this article, you will learn how to find the length of a string without using a string header file and loops in C. I will explain two ways to solve the problem of finding the string length without <string.h> and loop.

But before understanding the solution let’s first understand what string is in C.

In C programming language, a string is an array of characters that is terminated with a null character '\0'. The length of a string will be determined by counting all the characters in the string (except for the null character).

I have already written a blog post to find the string length using the strlen and loop; if you want you can check.

Now let’s come to the topic and see the two ways to find the length of a string without string.h and loop.

1. Using the recursive method:

You can use recursion to find the length of the given string. See the following example which finds the length of the string.

// C program to find string len using recursion
#include <stdio.h>

#define  BUFFER_SIZE 100


void getLenOfString(const char *pString, int len)
{
    if(pString[len] == '\0')
    {
        printf("String len is:%d\n", len);
        return;
    }
    getLenOfString(pString,len+1);
}

int main()
{
    char string[BUFFER_SIZE] = {0};

    //get String
    printf("Give a string : ");
    scanf("%s",string);

    printf("Entered string is:%s\n", string);

    //find string len
    getLenOfString(string, 0);

    return 0;
}

Output:

Give a string : Aticleworld
Entered string is:Aticleworld
String len is:11

 

Explanation: 

The function getLenOfString() calls itself until the null character is found in the above example code. And for each call increment the variable len that represents the length of the string.

 

2. Using the printf():

Using the printf() you can also get the length of the string. The printf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred.

#include <stdio.h>

#define  BUFFER_SIZE 50

int main()
{
    // entered string
    char str[BUFFER_SIZE] = "Aticleworld";

    // printing entered string
    printf("Entered String is:");

    // printf returns length of string
    const int strLen
        = printf("%s\n", str);

    // printing length
    printf("String Length is: %d", (strLen - 1));
}

Output:

Entered String is:Aticleworld
String Length is: 11

 

Recommended Articles for you: