String Comparison in C. String comparison is a common operation in programming, String comparison is used to check whether two strings are equal or not. In the C language, comparing strings involves checking each character in the String to ensure the match. In this article, we will write a C program for String comparison.
Table of Contents
Understanding String Comparison in C
In C, strings are the arrays of characters(char data type) terminated by a null character(‘\0’). To compare to strings, we need to examine each corresponding character in both strings until we find a mismatch or reach the end of either string. The comparison is case sensitive, that is upper case and lower case characters are written as distinct.
C Program for String Comparison
Let’s write a simple C program that compares strings by using a custom string comparison function as well as by using the standard library function ‘strcmp()’.
#include <stdio.h>
#include <string.h>
// Function to perform string comparision
int customStrcmp(char *str1, char *str2)
{
while (*str1 != '\0' && *str2 != '\0' && *str1 == *str2)
{
str1++;
str2++;
}
return (*str1 - *str2);
}
void main()
{
char strA[] = "Gang For Code";
char strB[] = "Gang For Code";
// String comparision by using strcmp()
if (strcmp(strA, strB) == 0)
{
printf(" By using strcmp()- both strings are equal\n");
}
else
{
printf(" By using strcmp()- both strings are not equal\n");
}
// string comparision by using custom function
if (customStrcmp(strA, strB) == 0)
{
printf(" By using custom function- both strings are equal\n");
}
else
{
printf(" By using custom function- both strings are not equal\n");
}
}
Output
Explanation of C Program for String Comparison
- The function
customStrcmp
iterates through the characters of both strings until a mismatch is found or the end of either string is reached. It returns the difference between the ASCII values of the mismatched characters. - Inside the main function, there are two strings declared- strA, and strB.
- We used a standard library function
strcmp()
to compare the strings and print the result. - We also use the custom function
customStrcmp()
to compare the strings and print the result.
Happy Coding
1 thought on “String Comparison in C”