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 variablelength
to store the length of the string. - It prompts the user to input a string using the
printf()
function and reads the input using thegets()
function. - The program then uses the
strlen()
function to get the length of the string entered by the user and stores it in thelength
variable. - Finally, it prints out the length of the string using the
printf()
function.
Thanks for reading!