C Program to Compare Two Strings

Following C program ask the user to enter the two string to check whether the two strings are equal or not using strcmp() function of string.h library. Here, strcmp() function takes two argument like strcmp(str1, str2) to compare the two string to check whether it is equal or not. If the two strings are equal then it will return 0 and if the two strings are not equal then it will return 1. So 0 for equal and 1 for not equal.

Program1:

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
    clrscr();
    char str1[100], str2[100];
    printf("Please Enter the First String : ");
    gets(str1);
    printf("Please Enter the Second String : ");
    gets(str2);
    if(strcmp(str1, str2)==0)
    {
        printf("Both the strings are equal");
    }
    else
    {
        printf("Both the strings are not equal");
    }
    getch();
}

Program 2:


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

int main()
{
     char string1[5],string2[5];
         int i,temp = 0;

          printf("Please Enter the First String : ");
         gets(string1);

         printf("Please Enter the Second String : ");
         gets(string2);

         for(i=0; string1[i]!='\0'; i++)
         {
                  if(string1[i] == string2[i])
                  temp = 1;
                  else
                  temp = 0;
         }

         if(temp == 1)
            printf("Both the strings are equal");

         else

         printf("Both the strings are not equal");

    return 0;
  getch();
}

Run1:



Run2:


No comments:

Post a Comment

100 C Programs with Code and Output

Program 1: C Program To Read Two Numbers And Print The Sum Of Given Two Numbers. Program 2: C Program To Read Three Numbers And Prin...