You are here

C string length program

C string length program: This program finds 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

  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. int main()
  5. {
  6.   char a[100];
  7.   int length;
  8.  
  9.   printf("Enter a string to calculate it's length\n");
  10.   gets(a);
  11.  
  12.   length = strlen(a);
  13.  
  14.   printf("Length of the string = %d\n", length);
  15.  
  16.   return 0;
  17. }

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 then increment the counter by one. Once the null character is found the counter equals length of the string.

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.   char s[1000];
  6.   int c = 0;
  7.  
  8.   printf("Input a string\n");
  9.   gets(s);
  10.  
  11.   while (s[c] != '\0')
  12.     c++;
  13.  
  14.   printf("Length of the string: %d\n", c);
  15.  
  16.   return 0;
  17. }

Function to find string length:

  1. int string_length(char s[]) {
  2.    int c = 0;
  3.  
  4.    while (s[c] != '\0')
  5.       c++;
  6.  
  7.    return c;
  8. }

C program to find length of a string using recursion

  1. #include <stdio.h>
  2.  
  3. int string_length(char*);
  4.  
  5. int main()
  6. {
  7.    char s[100];
  8.  
  9.    gets(s);
  10.  
  11.    printf("Length = %d\n", string_length(s));
  12.  
  13.    return 0;
  14. }
  15.  
  16. int string_length(char *s) {
  17.    static int c = 0;
  18.  
  19.    while (s[c] != '\0') {
  20.       c++;
  21.       string_length(s+1);
  22.    }
  23.  
  24.    return c;
  25. }

Function to find string length using pointers

  1. int string_length(char *s) {
  2.    int c = 0;
  3.    
  4.    while(*s[c] != '\0')
  5.       c++;
  6.      
  7.    return c;
  8. }