Like Us On Facebook

Follow Us On Twitter

Drop Down Menu

Sunday 4 August 2013

C Code To Find The Length Of a String

Hello guys,
In this post, I'll explain the C Code how to find the length of a string, by 2 methods, first by using strlen() function and second by normal programming.

Length of a string is defined to be the number of characters in it excluding the null character '\0'. To find the length of a string, we need to scan through the string, count the number of characters till the null character is reached. C provides a built-in function namely, strlen() to find the length of a string. 

C Program To Find The Length Of a String:


/* Double-Click To Select Code */

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

void main()
{ 
 char str[100];
 int i,length;
 clrscr();

 printf("Enter a String: ");
 gets(str);

/* Finding the length of str without using strlen() begins */

 length=0;
 for(i=0 ; str[i]!='\0' ; i++)
 length++;
 printf("\nLength of '%s' = %d\n",str,length);

/* Finding the length of str using strlen() begins */

 length = strlen(str);
 printf("Length of '%s' using strlen = %d \n",str,length);

 printf("\n\n *WWW.CODINGBOT.NET*");
 getch();
}

Program Explanation:

str is declared to be an array of char type and of size 100. Length and i are declared to be variables of int type. str is to collect the input string. Variable length is to collect the length of the string in str. The variable i is to scan through the string accessing each character.

A string is read into str through the keyboard  The following segment finds the length of str without strlen():

                          length = 0;
                          for(i=0 ; str[i] != '\0' ; i++)
                                  length++;

Length is initialized to 0 before scanning through the string begins. When the loop is entered, scanning through the string begins. During the course of scanning, if the character is not fund to be null character '\0', length is incremented by one. The loop is exited when the null character is reached. So, when the loop completes, length collects the length of str.
The length of str is found out using strlen() built-in function also.

Program Output:


C Code To Find The Length Of a String

Please Comment If You Liked The Post.



Do you like this post? Please link back to this article by copying one of the codes below.

URL: HTML link code: Forum link code: