C program to find the length of a string

C program to find the length of a string, in this article I will explain C program to find the length of a string with or without the strlen()string function, a loop will be used in c program to find the length of a string, the program will ask the user to input a string the program will print the length of a string. I will explain the different methods to find the length of a string.

you should have basic knowledge  c programming  like a loop, conditional statement, and string.


check this also:- Python program to count the total number of lines in a file


algorithm to find the length of the string using the while loop

  1. initialize all are variable
  2. ask a user to input a string
  3. store string in a variable str.
  4. declare a variable count and storecount=0
  5. execute loop till the termination of a loop, the loop will terminate when str[i] will be null.
  6. print count, the count will be the length of a string

C program to find the length of a string

#include<stdio.h>
int main()
{
    char str[50],count;
    printf("Enter string: ");// input from the user
    gets(str);
    count=0; //initailize count as zero
    int i=0;
    //while loop will terimante while str[i] will be NULL
    while(str[i]!=NULL)
    {
        count++;
        i++;
        //increasing count variable
    }
    printf("length of a string: %d",count);
}

Sample example C program to find the length of a string

example 1:
Enter string: dog is a pet animal
length of a string : 19

example 2:
Enter string: c is a programing language
length of a string : 26

example 3:
Enter string: length of a string
length of a string : 18

check this also:-  c program to calculate compound interest using function


C program to find the length of a string using strlen() function.

strlen() function in c-The C library function size_t strlen(const char *str) find the length of the string, but it does not include the terminating null character. strlen( ) function counts the number of characters in a given string and returns the integer value.It didn’t count the null or ‘\0’ character. because ‘\0’ character indicates the end of the string.

#include<stdio.h>
#include<string.h>
int main()
{
 char str[50],count;
 printf("Enter string: ");// input from the user
 gets(str);
 count=0; //initailize count as zero
 int i=0;
 //while loop will terimante while str[i] will be NULL
 int length=strlen(str);
 printf("%d",length);
}
C program to find the length of a string
   C program to find the length of a string

FINAL WORD:- 

hope you like this article if you have any doubt or problem regarding C program to find the length of a string hen you can feel free to ask the question. So, write your problem in the comment box. Because we are here to solve your all doubt.

Leave a Reply

Your email address will not be published. Required fields are marked *