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.
Prerequisites
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.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
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.
Program code:-
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 |
/* C program to Compare Two Strings */ #include <stdio.h> #include <string.h> int main() { //DECLARING THE VARIABLES. char String1[100], String2[100]; int i; //TAKING INPUT STRING ONE FROM THE USER printf("\n Please Enter the First String : "); gets(String1); //TAKING INPUT STRING TWO FROM THE USER printf("\n Please Enter the Second String : "); gets(String2); //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"); } else { //PRINTING IF STING ONE IS EQUAL TO STRING TWO printf("\n string 1 is Equal to string 2"); } return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- string1[100] = it will hold the string value.
- string2[100] = 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.