C program to Compare Two Strings without using strcmp() function
Last Updated :
06 Sep, 2021
Given two strings s1 and s2, the task is to write C program compare the two strings without using strcmp() function. If string are equal then print “Equal strings” else print “Unequal strings”.
Examples:
Input: s1 = “geeksforgeeks”, s2 = “geeks”
Output: Unequal Strings
Input: s1 = “geeksforgeeks”, s2 = “geeksforgeeks”
Output: Equal Strings
Approach: There are three possible cases occur when we compare two strings:
- Both the strings are the same means difference of ASCII value between both the strings is 0.
- Both the strings are different means ASCII value of first not matching character in the first string is less than the second string then the difference between both the strings is (<0).
- Both the strings are different means ASCII value of first not matching character in the first string is greater than the second string then the difference between both the strings is (>0).
Based on the above three conditions, the idea is to compare each character of the given strings one by one whenever condition 2 or 3 occurs then print “Unequal strings” else print “Equal strings”.
Below is the implementation of the above approach:
C
#include <stdio.h>
void compareStrings( char * x, char * y)
{
int flag = 0;
while (*x != '\0' || *y != '\0' ) {
if (*x == *y) {
x++;
y++;
}
else if ((*x == '\0' && *y != '\0' )
|| (*x != '\0' && *y == '\0' )
|| *x != *y) {
flag = 1;
printf ( "Unequal Strings\n" );
break ;
}
}
if (flag == 0) {
printf ( "Equal Strings\n" );
}
}
int main( void )
{
char s1[20] = "python" ;
char s2[20] = "dsa" ;
compareStrings(s1, s2);
return 0;
}
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...