You are here

C string length program

C string length program: This program prints length of a string, for example, length of the string "C programming" is 13 (space character is counted). The null character isn't counted when calculating string length. To find length of a string, we can use strlen function of "string.h." C program to find length of a string without using strlen function, recursion.

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 the string = %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 isn't a null character increment the counter by one. Once the null character is found the counter equals 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;
}

C program to find length of a string using recursion

#include <stdio.h>
 
int string_length(char*);
 
int main() 
{
   char s[100];
 
   gets(s);
 
   printf("Length = %d\n", string_length(s));
 
   return 0;
}
 
int string_length(char *s) {
   static int c = 0;
 
   while (s[c] != '\0') {
      c++;
      string_length(s+1);
   }
 
   return c;
}

Function to find string length using pointers

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