A program to compare two strings without using library function
C Programming Language 069
The following code shows how to write a program to compare two strings without using library function.
Program
#include <stdio.h>
void main()
{
char str1[30], str2[30];
int i, equal = 1, len1 = 0, len2 = 0;
printf("Enter string 1: ");
gets(str1);
printf("Enter string 2: ");
gets(str2);
for (i = 0; str1[i] != '\0'; i++)
{
len1++;
}
for (i = 0; str2[i] != '\0'; i++)
{
len2++;
}
if (len1 != len2)
{
equal = 0;
}
else
{
for (i = 0; str1[i] != '\0'; i++)
{
if (str1[i] != str2[i])
{
equal = 0;
break;
}
}
}
if (equal == 1)
{
printf("Both strings are equal");
}
else
{
printf("Both strings are not equal");
}
printf("\n");
}
Result
Enter string 1: hello
Enter string 2: hello
Both strings are equal
Enter string 1: hello
Enter string 2: world
Both strings are not equal
Enter string 1: a
Enter string 2: bc
Both strings are not equal
Last Updated on
Comments