Tuesday, April 30, 2013

c Program to Compare Two Strings Without using strcmp() .


//Program to Compare Two Strings Without using strcmp()

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char string1[5],string2[5];
int i,temp = 0;
printf("Enter the string1 value:\n");
gets(string1);
printf("\nEnter the String2 value:\n");
gets(string2);
for(i=0; (string1[i]!='\0')||(string2[i]!='\0'); i++)
{
if(string1[i] != string2[i])
{
temp = 1;
break;
}


}
if(temp == 0)
printf("Both strings are same.");
else
printf("Both strings not same.");
    return 0;
}

It takes the 2 strings .Let it be string1 and string2 .At the beginning of each array ,the for loop checks whether the string values at the corresponding positions are equal or not.If it is not ,then temp takes value 1 and exit(break) from the loop.The loop continue until the end of strings ie '\0'.If the temp value is '0' then the strings are same...

6 comments:

  1. How to do it for more than 2 strings ??

    ReplyDelete
  2. Make use of the string sorting program logic.You can find the program here itself.

    ReplyDelete
  3. If the 1st string is 'BE' and the 2nd string is ' BEE '.
    Then this program would give a wrong result

    ReplyDelete
  4. I debugged .Now it's working perfectly.Thanks..

    ReplyDelete
  5. how to sort two strings without using string function??

    ReplyDelete