Wednesday, May 18, 2011

strcmp and strncmp in C

strcmp function in c

int strcmp(char * str1,char * str2)
strcmp function  returns a number eitheir 0, positive integer or negative integer

Return vaues:

positive integer       - is returned if string str1 is greater than string str2
0                           - if both the strings are equal
negative integer      -  if string str1 is less than the string str2

In this case comparisons happen using unsigned integers.

for example:
char * i = "hello";
char * j="hello1"; 
output will be a negative integer

 strncmp in C:

The syntax all are same .but in this case there is an extra argument for setting how many characters you want to compare.

int strncmp(char *str1,char * str2, int );

Functionality all are same.But here int parameter is to set no of characters to compare in two strings.

for example:
char * i = "hello";
char * j="hello1"; 
output will be 0 as we compare only 4 characters and it is same in both the strings.

No comments:

Post a Comment