Online visitors

People learning around the world

Online

—

Visitors exploring W3Schools

Online visitors by country Circles show approximate country locations. The country list provides the visitor counts.

Circles represent countries, not exact visitor locations.

Country

Online

Loading country activity…

    C Program to Compare Two Strings Without Using strcmp

    C Programming Examples


    This C program is used to compare two strings without using strcmp function.

    Program:

    #include<stdio.h>
    
    #include<string.h>
    int cmpstr(char s1[10], char s2[10]);
    
      int main() {
        char arr1[10] = "Nodalo";
        char arr2[10] = "nodalo";
        printf(" %d", cmpstr(arr1, arr2));
        //cmpstr() is equivalent of strcmp()
        return 0;
        }/
        /s1, s2 are strings to be compared
        int cmpstr(char s1[10], char s2[10]) {
        //strlen function returns the length of argument string passed
        int i = strlen(s1);
        int k = strlen(s2);
        int bigger;
        if (i < k) {
          bigger = k;
        }
        else if (i > k) {
          bigger = i;
        }
        else {
          bigger = i;
        }
        //loops 'bigger' times
        for (i = 0; i < bigger; i++) {
          //if ascii values of characters s1[i], s2[i] are equal do nothing
          if (s1[i] == s2[i]) {
          }
          //else return the ascii difference
          else {
            return (s1[i] - s2[i]);
          }
        }
        //return 0 when both strings are same
        //This statement is executed only when both strings are equal
        return (0);
      }
    

    Program Output:

    -32

    Explanation:

    cmpstr() is a function that illustrates C standard function strcmp(). Strings to be compared are sent as arguments to cmpstr().

    Each character in string1 is compared to its corresponding character in string2. Once the loop encounters a differing character in the strings, it would return the ASCII difference of the different characters and exit.



    Found This Page Useful? Share It!
    Get the Latest Tutorials and Updates
    Join us on Telegram

    Notifications

    Updates are enabled for this browser.

    Receive new tutorials, articles and learning resources. You can turn updates off anytime.