C program to Compare Two Strings without using strcmp():  Using string function it is easy to compare two string we only need to write only one function. But we can also compare the string without using string function.

How to compare two strings without using strcmp():
For this comparison of string , we use simple relational operators (== , > , < ) . Using this operator we compare two strings.
== operator will compare two string and returns 0
< operator will compare two string and returns value -1 if less
> operator will compare two string and returns 1 value if greater

Example:
H == H => 0 => both equal
H < J => -1 => H is less than J
J > I => 1 => J is greater than I

Algorithm to compare two strings in c

  1. Take two input string from the user
  2. Traverse both string a character one by one.
    Compare character using relational operators.
    If a character from string 1 == character from string 2
    Print both strings are equal
    If a character from string 1 < character from string 2
    Print String 1 is less than string2
    If a character from string 1 > character from string 2
    Print String 1 is greater than string2

C program to Compare Two Strings without using strcmp()

#include <stdio.h>
#include <conio.h>
void main ()
{
// declare variables
char str1 [30], str2 [30];
int i = 0, flag=0 ,len1, len2;

// take two string input
printf ("Enter string1");
gets (str1);
printf ("\n Enter string2");
gets (str2);
//length of both string
len1 = strlen (str1);
len2 = strlen (str2);
while (i < len1 && i < len2 )
{
if( str1 [i] == str2 [i])
{
i++;
continue;
}
if( str1 [i] < str2 [i])
{
flag = -1;
break;
}
if( str1 [i] > str2 [i])
{
flag = 1;
break;
}
}
if (flag == 0)
printf ("\n Both strings are equal ");
if(flag == -1)
printf ("\n string1 is less than string2 ");
if( flag == 1)
printf ("\n string1 is greater than string2 ");
}

Output:

 C program to Compare Two Strings without using strcmp()

Write A Comment