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
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
C program to compare string in c
printf("Enter a string 1\n");
printf("Enter a string 2\n");
printf("Both strings are equal\n");
printf("Both strings are not equal\n");
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”);
printf(“Enter a string 2\n”);
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”)