strcmp() in C
×


strcmp() in C

43

 strcmp() in C is like a judge that compares two strings.

 It looks at each character in both strings and decides which one comes first alphabetically.

 It's useful when you want to know if one word is greater than, less than, or equal to another word.

 Let's say we have two strings: "apple" and "banana".

 When we use strcmp() on these strings, it checks each letter one by one.

 It finds that "apple" comes before "banana" because "a" comes before "b" in the alphabet.

 So, strcmp() would return a negative number to indicate that "apple" is less than "banana".

Example:

// Program for strcmp() function in c
#include<stdio.h>
#include<string.h>
int main() { char str1[] = "apple"; char str2[] = "banana"; int result = strcmp(str1, str2); if (result < 0) printf("'%s' comes before '%s'\n", str1, str2); else if (result > 0) printf("'%s' comes after '%s'\n", str1, str2); else printf("'%s' and '%s' are the same\n", str1, str2); return 0; }

Output:

'apple' comes before 'banana'

Advantages of strcmp() 

 Easy Comparison: strcmp() simplifies comparing strings without having to check each character manually.

 Efficiency: It quickly evaluates strings, saving time and effort.

 Versatility: You can use strcmp() to compare strings of different lengths and contents.

 Standard Function: strcmp() is a standard function in C, widely used and understood by programmers.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments