How to Compare Strings in C


Introduction

Comparing strings in C is a common operation used to determine whether two strings are equal or if one comes before the other in lexicographic order. String comparison is essential for tasks like sorting, searching, and validation. In this guide, we'll explore how to compare strings in C and provide sample code to demonstrate different comparison techniques.


Comparing Strings with strcmp()

The most common way to compare strings in C is to use the

strcmp()
function from the
<string.h>
library. The function returns an integer value that indicates the relationship between the two strings:

  • If the return value is 0, the two strings are equal.
  • If the return value is less than 0, the first string is lexicographically less than the second string.
  • If the return value is greater than 0, the first string is lexicographically greater than the second string.

Here's an example:

#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "apple";
char str2[] = "banana";
int result = strcmp(str1, str2);
if (result == 0) {
printf("Strings are equal.\\n");
} else if (result < 0) {
printf("str1 comes before str2.\\n");
} else {
printf("str1 comes after str2.\\n");
}
return 0;
}

Comparing Strings with strncmp()

The

strncmp()
function is similar to
strcmp()
but allows you to specify a maximum number of characters to compare. This can be useful for comparing only a portion of strings:

#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "apple pie";
char str2[] = "apple sauce";
int result = strncmp(str1, str2, 5);
if (result == 0) {
printf("The first 5 characters are equal.\\n");
} else {
printf("The first 5 characters are not equal.\\n");
}
return 0;
}

Comparing Strings with strcasecmp() (Case-Insensitive)

If you need to perform a case-insensitive string comparison, you can use the

strcasecmp()
function (note that it's not a standard C library function, and its availability may vary depending on the system). This function ignores the case of characters when comparing strings:

#include <stdio.h>
#include <strings.h>
int main() {
char str1[] = "apple";
char str2[] = "APPLE";
int result = strcasecmp(str1, str2);
if (result == 0) {
printf("Strings are equal (case-insensitive).\\n");
} else {
printf("Strings are not equal (case-insensitive).\\n");
}
return 0;
}

Conclusion

String comparison is a fundamental operation in C programming. It allows you to determine the equality or ordering of strings, which is essential for various tasks. This guide has demonstrated different string comparison techniques using the

strcmp()
,
strncmp()
, and
strcasecmp()
functions. As you continue your journey in C programming, you'll find string comparison to be a valuable tool for data processing and decision-making.