C Program to Compare Two Strings

Compare two strings in C : The following program compares two strings (which are taken from user as input) using strcmp() function, using pointers, without using strcmp() function and using macros.

C program to compare two strings using strcmp()

/* Compare two strings using strmp() function */

#include<stdio.h>
#include<string.h>
 
int main()
{
	char str1[100], str2[100];
 
	printf("\n Enter first string:- ");
	gets(a);
 
	printf("\n Enter second string:- ");
	gets(b);
 
	if (strcmp(str1,str2) == 0)
		printf("\n Two strings entered are equal.\n");
	else
		printf("\n The strings are not equal.\n");
 
   return 0;
}

/* Output of above code:-

Enter first string:- Programming

Enter second string:- Programming

Two strings entered are equal.

*/

C program to compare two strings using pointers

 /* Compare two strings using pointer */

#include<stdio.h>
 
int string_comparison(char*, char*);
 
int main()
{
	char string1[1000], string2[1000]:
	int result;
   
	printf("\n Enter first string:- ");
	gets(string1);
   
	printf("\n Enter second string:- ");
	gets(string2);
   
	result = string_comparison(string1, string2);
   
	if(result == 0)
		printf("\n Two strings entered are same.\n");
	else
		printf("\n The strings entered are different.\n");
       
	return 0;
}
 
int string_comparison(char *string1, char *string2)
{
	while (*string1 == *string2)
	{
		if (*string1 == '\0' || *string2 == '\0')
		break;
         
		string1++;
		string2++;
	}
 
	if (*string1 == '\0' && *string2 == '\0')
		return 0;
	else
		return -1;
}

C program to compare two strings without using library functions

We can also compare two strings without using library functions.
/* Compare two strings without using library functions, by using user defined function */

#include 
 
int string_comparison(char [], char []);
 
int main()
{
	char string1[100], string2[100];
 
	printf("\n Enter first string:- ");
	gets(string1);
   
	printf("\n Enter second string:- ");
	gets(string2);
 
	if (string_comparison(string1, string2) == 0)
		printf("\n Equal strings.\n");
	else
		printf("\n Unequal strings.\n");
 
	return 0;
}
 
int string_comparison(char a[], char b[])
{
	int i = 0;
 
	while (a[i] == b[i])
	{
		if (a[i] == '\0' || b[i] == '\0')
		break;
		i++;
	}
   
	if (a[i] == '\0' && b[i] == '\0')
		return 0;
	else
		return -1;
}

Compare two strings using macros in C:

/* Aim: Define a macro EQUALSTR which
compares two strings x and y and gives 1 if 
equal and 0 otherwise. Use this macro to 
accept two strings from the user and check if they are equal. */

#include<stdio.h>
#include<string.h>

#define EQUALSTR(x,y) strcmp(x,y)==0?1:0 

void main()
{
	char str1[100],str2[100];

	printf("\n Enter two strings:- ");
	scanf("%s%s",str1,str2);

	if(EQUALSTR(str1,str2))
	printf("\n Two strings are equal \n \n");
	else
	printf("\n Two strings are not equal \n \n");
}

/* Output of above code:- 

 Enter two strings:- Halo Halo

 Two strings are equal

*/