codescracker


c

C Program to Compare Two Strings



« Previous Program Next Program »


Compare Two Strings in C

To compare two strings in C programming, you have to ask to the user to enter the two string and start comparing using the function strcmp(). If it will return 0, then both the string will be equal if it will not return 0, then both the string will not be equal to each other.

C Programming Code 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

/* C Program - Compare Two Strings */
		
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
	clrscr();
	char str1[100], str2[100];
	printf("Enter first string : ");
	gets(str1);
	printf("Enter second string : ");
	gets(str2);
	if(strcmp(str1, str2)==0)
	{
		printf("Both the strings are equal");
	}
	else
	{
		printf("Both the strings are not equal");
	}
	getch();
}

When the above c program is compile and executed, it will produce the following result. Above C Programming Example Output (for equal strings):

c program compare strings

Above C Programming Example Output (for unequal strings):

c program compare two strings

Same Program in Other Programming Language

You may also like same program in other programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test