Write a program to compare two strings without using the
strcmp() function

Answer Posted / kms

The following code compares the strings alphabetically:

For example:

1. "bite" is greater than "apple" even though length of bite
is less than apple. ( it is greater lexicographically)

2. "It is good" is lower than "It is great".

CODE -->

#include<stdio.h>
#include<conio.h>

void strings_compare(char [], char []);

void main()
{
char str1[50], str2[50];
clrscr();
flushall();
printf("String 1 : ");
gets(str1);
flushall();
printf("String 2 : ");
gets(str2);
strings_compare(str1,str2);
getch();
}

void strings_compare(char str1[], char str2[])
{
int i=0,j=0,flag1=0,flag2=0;
printf("\nString 1 : ");
puts(str1);
printf("\nString 2 : ");
puts(str2);
printf("\n");
while(str1[i] != '\0' || str2[j] != '\0')
{
if(str1[i] < str2[j])
{
flag1 = 1;
break;
}
if(str1[i] > str2[j])
{
flag2 = 1;
break;
}
else
{
i++;
j++;
}
}

if(flag1==1)
{
printf("\n\ns1 : %s is lower than s2 : %s",str1,str2);
}
else if(flag2 == 1)
{
printf("\n\ns1 : %s is greater than s2 : %s",str1,str2);
}
else
{
printf("\n\nBoth strings are equal...");
}
}

Is This Answer Correct ?    6 Yes 3 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Which type of language is c?

632


program to find out date after adding 31 days to a date in the month of febraury also consider the leap year

2557


Explain how are 16- and 32-bit numbers stored?

769


Is sizeof a keyword in c?

565


Can stdout be forced to print somewhere other than the screen?

603






Is exit(status) truly equivalent to returning the same status from main?

572


What is calloc in c?

646


How can you access memory located at a certain address?

656


what are # pragma staments?

1615


Explain is it better to bitshift a value than to multiply by 2?

693


What is null in c?

584


provide an example of the Group by clause, when would you use this clause

1687


By using C language input a date into it and if it is right?

558


Explain how can you tell whether a program was compiled using c versus c++?

560


What is the difference between scanf and fscanf?

646