C Program to Find the Length of a String using Inbuilt strlen() Function

In this article, we will write a C program to find the length of a string using the inbuilt strlen() function.

The program prompts the user to enter a string, calculates its length using strlen() function and prints its length back on the screen.

Sample Input:

Enter a string: Hello world

Sample Output:

Length of string is: 11

The strlen() function is an inbuilt function in C which is used to get the length of a string.

It takes a string as its argument and returns an integer value that represents the total number of characters in the string excluding the null('\0') character.

Here is its syntax:

int strlen(const char *str);

Here, str represents the string whose length is to be calculated.

The following C program shows how you can calculate the length of a string using the strlen() function:

// C program to find length of 
// a string using strlen() function

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

int main() {
    
    char str[100];
    int length;
    
    printf("Enter any string: ");
    gets(str);
    
    // Get the length of the string
    length = strlen(str);
    
    printf("The length of string is: %d", length);
    
    return 0;
}

Output:

Enter any string: Hello world
The length of string is: 11

Code Explanation:

  • The program starts by including the necessary header files: stdio.h and string.h.
  • It declares a character array str with a size of 100 and an integer variable length to store the length of the string.
  • It prompts the user to input a string using the printf() function and reads the input using the gets() function.
  • The program then uses the strlen() function to get the length of the string entered by the user and stores it in the length variable.
  • Finally, it prints out the length of the string using the printf() function.

Thanks for reading!

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.