String library function in C Language - Strlen() and Strcmp() examples with explanation | Coding classpoint

String library function 



There are several string library functions used to manipulate string and the prototypes for these functions are in header file “string.h”. Several string functions are 

strlen() 

This function return the length of the string. i.e. the number of characters in the string excluding the terminating NULL character. It accepts a single argument which is pointer to the first character of the string.

For example

strlen(“suresh”); 

It return the value 6.

In array version to calculate legnth:

int str(char str[]) 
{
 int i=0; 
while(str[i]!=’\o’) 
{
 i++; 
return i; 
}

Example: 

#include 
#include 
void main() 
char str[50]; 
print(”Enter a string:”);
gets(str); 
printf(“Length of the string is %d\n”,strlen(str)); 

Output: 
Enter a string: C in Depth 
Length of the string is 8 

strcmp()

This function is used to compare two strings. If the two string match, strcmp() return a value 0 otherwise it return a non-zero value. It compare the strings character by character and the comparison stops when the end of the string is reached or the corresponding characters in the two string are not same.

strcmp(s1,s2) 
return a value: 

    <0 when s1<s2
    =0 when s1=s2
    >0 when s1>s2

The exact value returned in case of dissimilar strings is not defined. We only know that if s1s2 then a positive value will be returned.

For example: 

/*String comparison…………………….*/ 

#include 
#include 
void main() 
char str1[10],str2[10]; 
printf(“Enter two strings:”); 
gets(str1); 
gets(str2); 
if(strcmp(str1,str2)==0) 
printf(“String are same\n”); 
else 
printf(“String are not same\n”); 
}

Output

Enter two strings
Cat
Dog
String are same

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.