C program to Compare Two Strings without using strcmp() function

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: Uequal Strings

Input: s1 = “geeksforgeeks”, s2 = “geeksforgeeks”
Output: Equal Strings

 

Approach: There are three possible cases occur when we compare two strings:



  1. Both the strings are the same means difference of ASCII value between both the strings is 0.
  2. 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).
  3. 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

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to compare the two strings
// without using strcmp() function
#include <stdio.h>
  
// Function that compares the two string
void compareStrings(char* x, char* y)
{
    int flag = 0;
  
    // Iterate a loop till the end
    // of both the strings
    while (*x != '\0' || *y != '\0') {
        if (*x == *y) {
            x++;
            y++;
        }
  
        // If two characters are not same
        // print the difference and exit
        else if ((*x == '\0' && *y != '\0')
                 || (*x != '\0' && *y == '\0')
                 || *x != *y) {
            flag = 1;
            printf("Uequal Strings\n");
            break;
        }
    }
  
    // If two strings are exactly same
    if (flag == 0) {
        printf("Equal Strings\n");
    }
}
  
// Driver Code
int main(void)
{
    // Given strings s1 and s2
    char s1[20] = "python";
    char s2[20] = "dsa";
  
    // Function Call
    compareStrings(s1, s2);
    return 0;
}

chevron_right


Output:

Uequal Strings

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.