Write a Program To calculate the string length in C

String length in C


String length C program to find 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 it. To find it, we can use strlen function of "string.h." C program to find length of a string without using strlen functionrecursion.

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;
}

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;
}

C program to find length of a string using recursion

#include<stdio.h>
int string_length(char [], int);
int main()
{
  char s[100];
  int l = 0; // Length is initialized to zero
  gets(s);
  printf("Length = %d\n", string_length(s, l));
  return 0;
}
int string_length(char s[], int l) {
  if (s[l] == '\0') // Base condition
    return l;
  l++;
  return (string_length(s, l));
}

No comments:

Post a Comment