C Program To Find The Length Of A String

This program  finds the length of the string.  We can find the length of a string using two methods: the first method to calculate length using a loop. Second method of calculating string length is by using a predefined string length method of the C language.

Program to calculate the length of the string using while loop

In this program a character array is declared. It takes input from the user using scanf function. Strings in C language are terminated with Null character. To calculate the length of the string variable count is declared as an integer data type which is initialised to zero. 

Character array is checked for null characters. While loop will be executed until Null character is encountered. Each time the loop is executed, the variable count is also incremented. When the While loop is terminated the variable count gives the length of the string.


//Program to calculate the length of the string using while loop




#include <stdio.h>

int main(void) 

{

        char str_len[1000];

        int i=0,count=0;

  

        printf("Input String: ");

        scanf("%s", str_len);

    

        while(str_len[i]!='\0')

       {

              count=count+1;

              i++;

        }

      printf("Length of input Str is %d", count);

      return 0;

}

Output:

Input String: thisisstring

Length of input Str is 12