In this tutorial you will learn about the C Program to Compare two Strings and its application with practical example.
C Program to Compare Two Strings
In this tutorial, we will learn to create a C program that will Compare Two Strings in C programming.
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic of C programming.
- For loop and its concepts in C Programming.
- Conditional Statements in C Programming.
1. Declaring the variables for the program.
2. Taking the input string one from the user.
3. Taking the input string two from the user.
4. Comparing the string one and two.
5. Printing the result .
6. End the program.
What is a string?
As we all know, the string is a collection of characters, symbols, digits, and blank spaces. In strings, only one variable is declared which can store multiple values.
Compare Two Strings
First will take the elements of string 1 from the user. Then will take the elements of string 2 from the user. Then will compare the two taken strings without using the predefined functions. i.e. compare them without using the strcmp function.
With the help of this program, we can Compare Two Strings.
/* C program to Compare Two Strings */
//DECLARING THE VARIABLES.
char String1, String2;
//TAKING INPUT STRING ONE FROM THE USER
printf("\n Please Enter the First String : ");
//TAKING INPUT STRING TWO FROM THE USER
printf("\n Please Enter the Second String : ");
//COMPARING STRINGS WITHOUT USING THE STRCMP()
for(i = 0; String1[i] == String2[i] && String1[i] == '\0'; i++);
if(String1[i] < String2[i])
//PRINTING IF STING ONE IS LESS THAN STRING TWO
printf("\n string 1 is Less than string 2");
else if(String1[i] > String2[i])
//PRINTING IF STING TWO IS LESS THAN STRING ONE
printf("\n string 2 is Less than string 1");
//PRINTING IF STING ONE IS EQUAL TO STRING TWO
printf("\n string 1 is Equal to string 2");
In the above program, we have first initialized the required variable.
- string1 = it will hold the string value.
- string2 = it will hold the string value.
- i = it will hod the integer value that will control the for loop
Taking Input string 1 from the user.
Taking Input string 2 from the user.
Printing Output compared string.