Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 23 Aug, 2020

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




// 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;
}
Output:
Uequal Strings

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

Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.




My Personal Notes arrow_drop_up
Recommended Articles
Page :