June 24, 2019

Compare Two Strings Without strcmp

The following is a C Program To Compare Two Strings Without strcmp on screen after taking input from the user. Previously I have posted about the same only using the strcmp command. You can go check that out first. Let's get started.

Compare Two Strings Without strcmp
Compare Two Strings Without strcmp

Overview:


Commands

gets() function is used to obtain input as a string and printf() function is used to print the string on the screen.
cmpstr() is a function that illustrates C standard function strcmp(). Strings to be compared are sent as arguments to cmpstr().

Program

#include<stdio.h>
#include<conio.h>
#include<string.h>
int cmpstr(char s1[10],char s2[10]);
void main()
{
    char arr1[10]="Demochar";
    char arr2[10]="demochar";
    clrscr();
    printf(" %d", cmpstr(arr1, arr2));
    /*cmpstr() is equivalent of strcmp()*/
    getch();
}
    /*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 greater;
    if(i<k) 
    {
      greater=k;
    }
    else if(i>k)
    {
      greater=i;
    }
    else
    {
      greater=i;
    }
    /*loops 'greater' times*/
    for (i=0;i<greater;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);
}


Output

Different Output for Equal and Unequal Strings
Different Output for Equal and Unequal Strings

All programs compiled in this post are compiled in AnDOSBox.

Explanation

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

Books I Prefer:






I hope this article was helpful to understand C Program To Compare Two Strings Without strcmp! Comment below, if you've got any question. Head back soon for another interesting article on C Programming.

0 Comments

Post a Comment

Read Comment Policy before commenting.