You are here

String length in C

String length

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

Length of string in C language

#include <stdio.h>
#include <string.h>

int main()
{
  char a[100];
  int length;

  printf("Enter a string to calculate its 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 then increment the counter by one. Once the null character is found the counter equals the length of the string.

#include <stdio.h>

int main()
{
  char s[1000];
  int c = 0;

  printf("Input a string\n");
  gets(s);

  while (s[c] != '\0')
    c++;

  printf("Length of the string: %d\n", c);

  return 0;
}

Function to find string length:

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) {
  if (*s == '\0') // Base condition
    return 0;

  return (1 + string_length(++s));
}

Function to find string length using pointers

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