c program to calculate length of string using strlen() function

In this example, we display length of string entered by user.

Find the Length of a String using loop

	
#include <stdio.h>
#include <string.h>
    
int main()
{
    char Str[1000];
    int i;
    
    printf("Enter the String :: ");
    scanf("%s", Str);
    
    for (i = 0; Str[i] != '\0'; ++i);
    
    printf("Length of String is %d", i);
    
    return 0;
}
	

Output :

	
Enter the String :: abcde
Length of String is 5
	

Find the Length of a String using strlen() function

	
        #include <stdio.h>
        #include <string.h>
          
        int main()
        {
            char Str[1000];
            int i;
          
            printf("Enter the String: ");
            scanf("%s", Str);
          
            printf("Length of Str is %ld", strlen(Str));
          
            return 0;
        }
	

Output :

	
Enter the String: abcde
Length of Str is 5
	

strlen() function is used for find length of string and it's a in-built function provided by c programming. We must include <string.h> heder file to use this function.


Share your thoughts

Ask anything about this examples