Compare Two Strings
This operation is used to compare two strings. Two strings are said to be equal only when all the characters at corresponding positions in both string are equal.
In order to compare two strings, first we have to find length of both strings. If length of both strings is not equal then strings are not equal. But if length of both strings is equal then we have to compare each character of both strings. If all the characters at corresponding positions in both strings are equal then strings are said to be equal.
Algorithm to Compare Two Strings
| Step 1: | Length = 0 EQUAL = 0 |
| Step 2: | Length1 = strlen (s1) Length2 = strlen (s2) |
| Step 3: | If (Length1 ≠ Length2) then Write “Strings are not equal” |
| Step 4: | Repeat step 5 while s1 [Length] ≠ NULL |
| Step 5: | If s1 [Length] ≠ s2 [Length] then EQUAL = 1 Length = Length +1 Else Length = Length + 1 |
| Step 6: | If EQUAL = 0 then Write “Strings are equal” Else Write “Strings are not equal” |
Program to Compare Two Strings
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char *s1,*s2;
void strcomp(char *s1,char *s2);
clrscr();
puts("Enter string1:");
gets(s1);
puts("Enter string2:");
gets(s2);
strcomp(s1,s2);
getch();
}
void strcomp(char *s1,char *s2)
{
int length=0;
int EQUAL=0;
int length1=strlen(s1);
int length2=strlen(s2);
if(length1!=length2)
printf("String Not Equal");
else
{
while(s1[length]!='\0')
{
if(s1[length]!=s2[length])
{
EQUAL=1;
length=length+1;
}
else
{
length=length+1;
}
}
if(EQUAL==1)
printf("String Not Equal");
else
printf("String Equal");
}
}