How to Compare Two Strings in C
Use the strcmp() function declared in <string.h> to compare two null-terminated strings in C. The function compares the strings lexicographically and returns zero when they are equal, a negative value when the first string comes before the second, or a positive value when the first string comes after the second.
Do not use == to compare the text stored in two character arrays or string pointers. The == operator compares addresses in this context, not the character sequences.
strcmp() Syntax for C String Comparison
int strcmp(const char *str1,const char *str2);
The two arguments are:
- str1: a pointer to the first null-terminated string.
- str2: a pointer to the second null-terminated string.
Both pointers must refer to valid null-terminated byte strings. Passing a null pointer or an array without a terminating \0 results in undefined behavior.
What Does strcmp() Return in C?
strcmp(str1, str2) == 0: the strings contain the same sequence of characters.strcmp(str1, str2) < 0: the first differing character instr1has a lower value than the corresponding character instr2.strcmp(str1, str2) > 0: the first differing character instr1has a higher value than the corresponding character instr2.
Only the sign of a nonzero result is portable. Do not assume that strcmp() will return exactly -1 or 1. It does not return NULL when strings differ.
How strcmp() Compares Characters
strcmp() compares corresponding characters from left to right until it finds a difference or reaches the terminating null character. The comparison is based on the values of the characters interpreted as unsigned char; it is not based on string length alone.
For example, comparing "apple" with "banana" produces a negative result because 'a' has a lower character value than 'b'. Comparing "cat" with "catalog" also produces a negative result: the first three characters match, but the null character ending "cat" comes before the next character in "catalog".
The comparison is case-sensitive. Therefore, "Apple" and "apple" are not equal.
Compare Strings with strcmp() in a C Program
The following program compares "apple" and "banana". In production code, it is clearer to call strcmp() once and store its result when more than one condition must be tested.
C Program
#include <stdio.h>
#include <string.h>
int main()
{
char s1[]="apple";
char s2[]="banana";
if(strcmp(s1,s2)==0)
printf("equal");
if (strcmp(s1,s2)<0)
printf("s1 less than s2");
if(strcmp(s1,s2)>0 )
printf("s1 greater than s2");
return 0;
}
Output
s1 less than s2
Store the strcmp() Result Before Testing It
#include <stdio.h>
#include <string.h>
int main(void) {
const char first[] = "apple";
const char second[] = "banana";
int result = strcmp(first, second);
if (result == 0) {
printf("The strings are equal.\n");
} else if (result < 0) {
printf("%s comes before %s.\n", first, second);
} else {
printf("%s comes after %s.\n", first, second);
}
return 0;
}
Why the == Operator Does Not Compare C String Contents
A C string is stored as an array of characters ending with \0. In most expressions, an array name is converted to a pointer to its first element. Consequently, an expression such as first == second compares the two pointer values. Separate arrays can contain identical text while occupying different addresses.
#include <stdio.h>
#include <string.h>
int main(void) {
char first[] = "C language";
char second[] = "C language";
printf("Address comparison: %s\n",
first == second ? "equal" : "different");
printf("Content comparison: %s\n",
strcmp(first, second) == 0 ? "equal" : "different");
return 0;
}
Address comparison: different
Content comparison: equal
The address comparison in this example is also diagnosed by many compilers because the two array addresses are known to be distinct. Use strcmp() whenever the required operation is a comparison of string contents.
Compare the First n Characters with strncmp()
Use strncmp() when only the first n characters should be compared. It stops at the first difference, at a null character, or after examining at most n characters.
int strncmp(const char *str1, const char *str2, size_t n);
#include <stdio.h>
#include <string.h>
int main(void) {
const char first[] = "TutorialKart";
const char second[] = "TutorialPoint";
if (strncmp(first, second, 8) == 0) {
printf("The first 8 characters are equal.\n");
} else {
printf("The first 8 characters are different.\n");
}
return 0;
}
The first 8 characters are equal.
strncmp() is useful for checking a fixed prefix, but the value of n must match the intended rule. For example, testing only the first three characters would treat "cat" and "catalog" as matching prefixes, not as equal complete strings.
Compare Strings Read with fgets()
fgets() limits the number of characters written to an array, making it safer than the obsolete gets() function. When input is read from a line, remove the trailing newline before comparing the strings.
#include <stdio.h>
#include <string.h>
int main(void) {
char first[100];
char second[100];
printf("Enter the first string: ");
if (fgets(first, sizeof first, stdin) == NULL) {
return 1;
}
printf("Enter the second string: ");
if (fgets(second, sizeof second, stdin) == NULL) {
return 1;
}
first[strcspn(first, "\n")] = '\0';
second[strcspn(second, "\n")] = '\0';
if (strcmp(first, second) == 0) {
printf("The strings are equal.\n");
} else {
printf("The strings are different.\n");
}
return 0;
}
Legacy Recursive String Comparison Example
The following historical example attempts to compare strings recursively. It is retained for reference, but it should not be used as production C code: CompareStrings() is called before it is declared, a semicolon is missing after return -2, recursive results are not returned, and gets() cannot prevent a buffer overflow. Prefer strcmp() or the safe manual implementation shown later.
C Program
#include <string.h>
#include <stdio.h>
int main() {
char str[100],s[100];
printf("enter strings to compare");
gets(str);
gets(s);
printf("the result of comparison is %d\n",CompareStrings(s, str));
return 0;
}
int CompareStrings(char *s, char *s1) {
// if one of the pointer is a NULL pointer return directly -2
// in order to stop the process
if(s==NULL || s1==NULL)
return -2
if(strcmp(s,s1)==0) // the two strings are identical
return 0;
if((s[0])==(s1[0]) && (s[0])==((s1+1)[0]))
CompareStrings(s, ++s1);
else if((s[0])==(s1[0]) && (s1[0])==((s+1)[0]))
CompareStrings(++s, s1);
else if((s[0])==(s1[0]))
CompareStrings(++s, ++s1);
else
return -1;
}
A Correct Recursive String Comparison Function
This version compares one character at a time and returns the result of each recursive call. Casting to unsigned char gives the comparison the same character-value behavior expected from strcmp().
int compare_recursive(const char *first, const char *second) {
unsigned char a = (unsigned char)*first;
unsigned char b = (unsigned char)*second;
if (a != b) {
return (a > b) - (a < b);
}
if (a == '\0') {
return 0;
}
return compare_recursive(first + 1, second + 1);
}
Compare C Strings Manually with Pointers
A manual comparison function can advance two pointers while their characters match. The historical example below demonstrates the basic technique for checking equality. It also uses gets(), so replace its input code with fgets() before compiling it in a modern program.
C Program
#include<stdio.h>
int compstring(char* s1, char* s2);
int main() {
char s1[100], s2[100];
int result;
printf("Input a string1\n");
gets(s1);
printf("Input a string2\n");
gets(s2);
result = compstring(s1,s2);
if (result == 0)
printf("The strings are same.\n");
else
printf("The strings are different.\n");
return 0;
}
int compstring(char *s1, char *s2) {
while (*s1== *s2) {
if (*s1 == '\0' || *s2 == '\0')
break;
s1++;
s2++;
}
if (*s1 == '\0' && *s2== '\0')
return 0;
else
return -1;
}
A Manual strcmp()-Style Pointer Function
int compare_strings(const char *first, const char *second) {
while (*first != '\0' && *first == *second) {
first++;
second++;
}
unsigned char a = (unsigned char)*first;
unsigned char b = (unsigned char)*second;
return (a > b) - (a < b);
}
This function returns -1, 0, or 1. Standard strcmp() may return other negative or positive values, but both functions use the same three result categories.
Case-Sensitive and Case-Insensitive String Comparison in C
strcmp() and strncmp() are case-sensitive, so "C" and "c" compare as different strings. The ISO C standard library does not define a general case-insensitive equivalent of strcmp(). Some platforms provide functions such as strcasecmp() or _stricmp(), but these are platform-specific.
A portable case-insensitive comparison can convert corresponding characters with tolower() from <ctype.h>. Pass values as unsigned char before calling character-conversion functions. Also note that this simple approach follows the active C locale and is not a complete Unicode text-comparison solution.
Common C String Comparison Mistakes
- Using
==for text: it compares pointer values rather than the characters stored in the strings. - Testing
strcmp()as a Boolean equality check: equal strings return zero, so usestrcmp(a, b) == 0. - Expecting exactly -1 or 1: the C interface guarantees only a negative, zero, or positive result.
- Passing a null pointer:
strcmp()requires valid pointers to null-terminated strings. - Leaving the newline from
fgets():"apple\n"does not equal"apple". - Using
gets(): it cannot limit input length and was removed from the C standard; usefgets(). - Assuming locale-aware natural-language ordering:
strcmp()compares byte values and does not implement dictionary collation.
Frequently Asked Questions About Comparing Strings in C
Can I use == to compare strings in C?
No. For character arrays or pointers, == compares addresses. Use strcmp(first, second) == 0 to test whether two null-terminated strings contain the same characters.
What does strcmp() return when two C strings are equal?
It returns 0. A negative result means the first string compares before the second, while a positive result means it compares after the second.
How do I compare only part of a string in C?
Use strncmp(first, second, n) to compare at most the first n characters. A zero result means the examined prefixes match; it does not necessarily mean that the complete strings are equal.
Does strcmp() compare string lengths?
Not directly. It compares characters from left to right. Length affects the result only when all characters match up to the point where one string reaches its terminating null character first.
Is strcmp() case-sensitive?
Yes. Uppercase and lowercase letters have different character values, so strings that differ only in letter case are not equal under strcmp().
C String Comparison Editorial QA Checklist
- Confirm that equality tests use
strcmp(a, b) == 0, nota == b. - Check that every string passed to a comparison function is null-terminated.
- Describe nonzero
strcmp()results by sign instead of assuming exact values. - Use
strncmp()only when prefix or bounded comparison is intended. - Remove trailing newlines before comparing input collected with
fgets(). - Avoid presenting
gets()as safe or current C input code. - State explicitly when a comparison is case-sensitive or platform-specific.
Choosing the Correct C String Comparison Method
Use strcmp() for complete, case-sensitive string comparison and strncmp() when only a specified prefix should be examined. Manual pointer or recursive functions can demonstrate how character-by-character comparison works, but the standard library functions are normally clearer and less error-prone. Continue with the C Tutorial for related C programming topics.
TutorialKart.com