C program to compare two strings is a simple string program which is used to compare two strings using String function in c.
In this tutorial we are going to learn new one of the important and simple program which is program to compare two strings.
Before learning to compare two string in c first we see what is string in c.
String in c
String in c is a collection of character. And it ends with the null character.
In c string has different string function such as strcmp, strrev, strlen etc.
Lets see compare string in c.
String compare in c
C strcmp : String compare in c
To compare two strings in c the string class provided one function strcmp() using this function we can compare two strings.
For using this function we need to include string.h header file.
Syntax for strcmp in c :
how to use strcmp in c
int len = strcmp(string);
This function returns an integer value.
strcmp returns 0 of both strings are equal
returns -1 if string 1 less than string 2
returns 1 if string 1 greater than string 2
Strcmp example in c :-
int v = strcmp(“technical”,”technical”);
v = 0
Both strings are equal.
Logic to compare two string in c
First we declare string.h header file. Next week take input string from user. Now using the strcmp() to compare two string. If strcmp returns 0 Print the both strings are equal.
Algorithm to compare two strings in c
1. Start
2. Declare variable
3. Take a string input from user
4. Compare two strings using string function
5. if strcmp returns 0 print both strings are equal
6. End
C program to compare string in c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#include<stdio.h> #include<string.h> main() { char str1[100],str2[100]; printf("Enter a string 1\n"); gets(str1); printf("Enter a string 2\n"); gets(str2); if(strcmp(str1,str2)==0) { printf("Both strings are equal\n"); } else { printf("Both strings are not equal\n"); } } |
Output ;

Explanation :-
1. a header files stdio.h and string.h as we are using string function.
2. Next write the main function from where the execution of program starts.
3. Declare the variables
str1 => to store the string 1
str2 => to store the string 2
flag => for flag
4. Next take two input string from user.
printf(“Enter a string 1\n”);
gets(str1);
printf(“Enter a string 2\n”);
gets(str2);
We use a gets() to take a input string from user.
Difference between scanf and gets is scanf don’t accept space in string but gets accepts space in string.
5. Example :-
str1 = technical
str2 = technical
6. Next we compare two strings using strcmp ()
flag=strcmp(str1,str2) => flag = 0
7. Next check flag value of flag = 0 print both strings are equal .
flag==0 => printf(“Both strings are equal\n”)
flag==-1 => printf(“String1 is less than string 2\n”)
flag==1 => printf(“String 1 is greater than string 2\n”)
Recommended posts
Find length of string using string function
Leave a Reply