strcmp()
is a standard library function in C used to compare two strings. It compares the characters of the strings one by one until a difference is found or the end of the string, represented by the null character '\0'
, is reached.
strcmp Function Header File
The header file for the strcmp
function is <string.h>
. Before using the strcmp
function, make sure to include this header file in your C code:
#include <string.h>
strcmp Function Prototype
int strcmp(const char *s1, const char *s2);
The strcmp
function compares the string pointed to by s1
with the string pointed to by s2
character by character, and returns when a difference is found or the null character '\0'
is encountered;
Parameter Explanation
s1
: A pointer to the first string;s2
: A pointer to the second string;
Return Value
The strcmp
function returns an integer greater than, equal to, or less than 0
;
The strcmp()
function compares the ASCII values of the two strings character by character. When the characters differ, it returns the difference between the two characters. If the strings are identical, it returns 0
.
strcmp Example Code
Compare if two strings are identical
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "world";
if (strcmp(str1,str2) == 0) {
printf("The two strings are identical.\n");
} else {
printf("The two strings are different.\n");
}
return 0;
}