The function int strcmp(const char *str1, const char *str2); compares string pointed by str1 with string pointed by str2. This function compares both string character by character. It will continue comparison until the characters mismatch or until a terminating null-character is reached.
Function prototype of strcmp
int strcmp(const char *str1, const char *str2);
- str1 : A pointer to a C string to be compared.
- str2 : A pointer to a C string to be compared.
Return value of strcmp
Return Value | Description |
---|---|
Positive (>0) | str2 is less than str1 |
Zero (==0) | str1 is equal to str2 |
Negative (<0) | str1 is less than str2 |
C program using strcmp function
The following program shows the use of strcmp function to compare two strings.
#include <stdio.h> #include <string.h> int main() { char firstString[100], secondString[100]; int response; printf("Enter first string\n"); scanf("%s", &firstString); printf("Enter second string\n"); scanf("%s", &secondString); response = strcmp(firstString, secondString, 5); if(response > 0){ printf("second String is less than first String"); } else if(response < 0) { printf("first String is less than second String"); } else { printf("first String is equal to second String"); } return(0); }
Output
Enter first string asdfg Enter second string ASDFG second String is less than first String
Enter first string testString Enter second string testString first String is equal to second String