Count Length of String
Count Length of String is nothing but just count number of character in the given String. For Example: String="India" in this string have 5 characters also this is the size of string.
Count length of String without using any library function.
/**************************************************
Count length of String
***************************************************/
#include< stdio.h>
#include< conio.h>
void main()
{
int i,count=0;
char ch[20];
clrscr();
printf("Enter Any String: ");
gets(ch);
for(i=0;ch[i]!='\0';i++)
{
count++;
}
printf("Length of String: %d",count);
getch();
}
Output
Enter any String: hitesh
Length of String: 6
Explanation of Code
Here gets() is a predefined function in "conio.h" header file, It recevie a set of character or String from keyboard.
for(i=0;ch[i]!='\0';i++)
{
count++;
}
Here we check the condition ch[i]!='\0' its means loop perform until string is not null, when string is null loop will be terminate.
Count length of String Using Library Function
/**************************************************
Count length of String
***************************************************/
#include< stdio.h>
#include< string.h>
int main()
{
char str[20];
int length;
printf("Enter any string: ");
gets(str);
length = strlen(str);
printf("Length of string: %d",length);
return 0;
}
Output
Enter any String: Kumar
Length of String: 5
Explanation of Code:
- Here gets() is a predefined function in "conio.h" header file, It recevie a set of character or String from keyboard.
- strlen() is a predefined function in "conio.h" header file which return length of any string.