You are here

C string length program

C string length program: This program prints length of a string, for example, consider the string "c programming" its length is 13. The null character is not counted when calculating string length. To find the length of a string, we can use strlen function of "string.h." C program to find length of a string without using strlen function

String length C program

#include <stdio.h>
#include <string.h>
 
int main()
{
   char a[100];
   int length;
 
   printf("Enter a string to calculate it's length\n");
   gets(a);
 
   length = strlen(a);
 
   printf("Length of entered string is = %d\n",length);
 
   return 0;
}

Download String length program.

Output of program:
String length C program output

String length in C without strlen

You can also find string length without strlen function. We create our function to find it. We scan all the characters in the string if the character is not a null character increment the counter by one. Once the null character is found the counter equals the length of the string.

#include <stdio.h>
 
int string_length(char []);
 
int main()
{
   char s[1000];
   int length;
 
   printf("Input a string\n");
   gets(s);
 
   length = string_length(s);
 
   printf("Length of \"%s\" = %d\n", s, length);
 
   return 0;
}
 
int string_length(char s[]) {
   int c = 0;
 
   while (s[c] != '\0')
      c++;
 
   return c;
}

Function to find string length using pointers

int string_length(char *s) {
   int c = 0;
 
   while(*s[c] != '\0')
      c++;
 
   return c;
}