C Program to Find Length of String

Here we will write a C program to find length of string. The length of the string “Computer” is 8.

Find the length of the string without using string manipulation library functions

To find the length we can use for loop or while loop. Below program uses the for loop.

#include<stdio.h>
int main()
{
   char str[200];
   int i;

   printf("Enter string: ");
   scanf("%[^\n]",str);

   for(i=0;str[i]!='\0';i++);

   printf("length of entered string is=%d",i);

   return 0;
}

Output:-

Enter string: Computer Corner
length of entered string is=15

The variable i is initialized with 0 inside for loop. Now, the condition str[i]!='\0' will be checked for every character of the string. When the condition is true then the value of the variable i will increment. At the end of the string, it encounters a null character (‘\0’) so condition becomes false and the variable i value will not increment, loop ended. Finally, we get the length of the string without using a predefined function strlen().

Length of string using strlen()

  • strlen() function returns the length of the string passed.
  • strlen() doesn’t count null character ‘\0’
  • The Required header file is string.h
#include<stdio.h>
#include<string.h>
int main()
{
   char a[20]="Computer";
   char b[20]={'C','O','R','N','E','R','\0'};
   char c[20];

   printf("Enter a string: ");
   scanf("%[^\n]",c);

   printf("Length of string %s =%ld\n",a,strlen(a));
   printf("Length of string %s =%ld\n",b,strlen(b));
   printf("Length of string %s =%ld\n",c,strlen(c));

   return 0;
}

Output:-

Enter a string: Programming
Length of string Computer =8
Length of string CORNER =6
Length of string Programming =11


Here C program to find the length of string, to take input from the user we can use gets() or fgets(). The fgets() function also newline character to the string. If you use fgets() function as shown below then you will get result = (actual length + 1). The gets() takes same length of input as [^\n] taken. For same string, gets() gives length 12 but for fgets() gives length 13.

Also See:- Why gets function is dangerous and should not be used

//Using fgets()
fgets(str, sizeof(str), stdin);
for(i=0;str[i]!='\0';i++);
// or
strlen(str);

Output:-

Enter string: Know Program
length of entered string is = 13

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Leave a Reply