Compare two strings without using library functions

Lets see how to compare two strings on the basis of ascii value of characters.

Lets say we have two strings s1 and s2.We compare these strings character by character.Only if both the characters are identical we move to the next character.If at any point , if both characters are not identical we make a decision about which string is greater and stop.


Code

#include<stdio.h>

int main() 
{
    char s1[20],s2[20];
    int i = 0;

    printf("\nEnter string1 : ");
    gets(s1);

    printf("\nEnter string2 : ");
    gets(s2);

    while(s1[i] == s2[i])
        i++;

    if(s1[i] > s2[i])
        printf("\n   s1 > s2");

    else if(s1[i] < s2[i])
        printf("\n   s1 < s2");

    else
        printf("\n   s1 = s2");

    return 0;
}


O/P




Code Tracing

     s1                        s2                     

i                         i                      
p r o g r a m             p r o G r a m           Identical,inc i

  i                         i
p r o g r a m             p r o G r a m           Identical,inc i

    i                         i                     
p r o g r a m             p r o G r a m           Identical,inc i

      i                         i                    
p r o g r a m             p r o G r a m           Ascii value(g)>Ascii value(G)
                                                  So, s1 > s2.
                                                  Stop.

No comments:

Post a Comment