Ad Code

Responsive Advertisement

strcmp() functionin C ? with example

 

Compare String: strcmp() in C


The strcmp(first_string, second_string) function compares two string and returns 0 if both strings are equal.

Here, we are using gets() function which reads string from the console.
c
#include <stdio.h> #
include <string.h> 
int main()
char str1[] = "apple"
char str2[] = "banana";
int result = strcmp(str1, str2); 
if (result == 0) { 
printf("The strings are equal.\n"); 
 } else if (result < 0) { 
printf("%s comes before %s in lexicographical order.\n", str1, str2); 
 } else
printf("%s comes after %s in lexicographical order.\n", str1, str2);
 }
return 0
}

In this example, the strcmp() function is used to compare the strings str1 and str2. Depending on the result, the program prints whether the strings are equal or which one comes before or after the other in lexicographical order.

It's important to note that the comparison is case-sensitive, meaning uppercase and lowercase letters are treated differently. If you want a case-insensitive comparison, you can use strcasecmp() (or _stricmp() on Windows) if your environment supports it.
c
int strcasecmp(const char *str1, const char *str2);


Post a Comment

0 Comments