C program to Compare Two Strings

Problem Description

Write a C Program to compare two strings.

What is a String?

String is a sequence of characters terminated by the special character ‘\0’. Strings can be compared with or without using the string function.

Example:

String1=”Hello”      String2=”Hello”      Both string are equal
String1=”Hello”      String2=”Hell”        String1 is greater
String1=”Hello”      String2=”Helz”       String2 is greater
Problem Solution

1. Take two strings as input.
2. Compare the two strings and display the result whether both are equal, or first string is greater than the second or the first string is less than the second string.
3. Exit.

For comparing two strings, we will look at the following approaches.

Method 1: Naive Approach (using loops)

In this approach, we will compare the two strings using loops.

advertisement
advertisement

Algorithm to compare two strings using loops:
Step 1: Start the Program.
Step 2: Input both the Strings.
Step 3: Iterate until characters of both strings are equal or the first string is completely iterated.
Step 4: Now compare both characters of strings.

  • If the ascii value of the first string character is greater than the second, print the first string is greater than the second.
  • Else If the ascii value of the first string character is less than the second, print the second string is greater than the first.
  • If the ascii value of the first string character is equal to the second. print, both strings are equal.

Step 5: End the Program.

Program/Source Code

Here is the source code of the C program to compare two strings using loops. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C program to Compare Two Strings using loops.
  3.  */
  4. #include <stdio.h>
  5.  
  6. int main ()
  7. {
  8. 	int count1 = 0, count2 = 0, flag = 0, i;
  9. 	char string1[30], string2[30];
  10.  
  11. 	printf ("Enter the First string\n");
  12. 	gets (string1);
  13.  
  14. 	printf ("Enter the Second string\n");
  15. 	gets (string2);
  16.  
  17. 	while (string1[count1] != '\0')
  18. 		count1 ++;
  19.  
  20. 	while (string2[count2] != '\0')
  21. 		count2 ++;
  22.  
  23. 	i = 0;
  24.  
  25. 	while (string1[i] == string2[i] && string1[i] != '\0')
  26. 	{
  27. 		i ++;
  28. 	}
  29.  
  30. 	if (string1[i] > string2[i])
  31. 		printf ("First string is greater than Second string\n");
  32. 	else if (string1[i] < string2[i])
  33. 		printf("Second string is greater than First string\n");
  34. 	else
  35. 		printf ("Both strings are EQUAL\n");
  36.  
  37. 	return 0;
  38. }
Program Explanation

1. Take two strings as input and store them in the arrays string1[] and string2[] respectively.
2. Count the number of characters in both the arrays and store the result in the variables count1 and count2.
3. Compare each character of the strings. If both the strings are equal then assign variable flag to zero or if string1 is greater than string2 then assign 1 to variable flag and break or if string1 is lesser than string2 then assign -1 to variable flag and break.
4. Print the output according to value of variable flag. (if the character of the first string is greater print first string is greater, if it is smaller print second string is greater else print both strings are equal.)

Time Complexity: O(n)
In while loop we are iterating over the first string until characters of both string are same or it is completely iterated, so time complexity is O(n), where n is length of first string.

Space Complexity: O(1)
Since no auxiliary space is required, space complexity is O(1).

Runtime Test Cases

Testcase 1: The first string entered here is “hello” and the second string is “hell”.

Enter the First string
hello
Enter the Second string
hell
First string is greater than Second string

Testcase 2: The first string entered here is “hello” and the second string is “helz”.

advertisement
Enter the First string
hello
Enter the Second string
helz
Second string is greater than First string

Method 2: Strcmp Function (Inbuilt Function in string.h library)

Strcmp is an inbuilt function used to compare two strings character by character.

Function Prototype: int strcmp(const char *s1,const char *s2)

advertisement

Return Values:

  • Zero, if both string are equal.
  • Less than 0, if ascii value of first non matching character of string1 is less than that of string2
  • Greater than 0, if ascii value of first non matching character of string1 is greater than that of string2

Algorithm to compare two strings using Strcmp Function:

Step 1: Start the Program
Step 2: Input both Strings
Step 3: Store value of strcmp function in result variable.
Step 4: If result = 0 then both strings are equal, if result > 0 then first string is greater else second string is greater.
Step 5: End the Program

Program/Source Code

Here is the source code of the C program to compare two strings using Strcmp Function. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C program to Compare Two Strings using Strcmp Function.
  3.  */
  4. #include <stdio.h>
  5. #include <string.h> 
  6. int main ()
  7. {
  8. 	char string1[30], string2[30];
  9.  
  10. 	printf ("Enter the First string\n");
  11. 	gets (string1);
  12.  
  13. 	printf ("Enter the Second string\n");
  14. 	gets (string2);
  15.  
  16.         int result=strcmp(string1,string2);
  17. 	if (result>0)
  18. 		printf ("First string is greater than Second string\n");
  19. 	else if (result < 0)
  20. 		printf("Second string is greater than First string\n");
  21. 	else
  22. 		printf ("Both strings are EQUAL\n");
  23.  
  24. 	return 0;
  25. }
Program Explanation

1. First input the two strings.
2. Now store the value of strcmp function in the result variable.
3. If result is greater than 0, print first string is greater, else if it is less than 0, print second string is greater, else both strings are equal.

Time Complexity: O(min(n,m))
The time complexity of strcmp function is O(min(n,m)) where n and m are the length of both the strings.

Space Complexity: O(1)
Since no auxiliary space is required, space complexity is O(1).

Runtime Test Cases

Testcase 1: The first string entered here is “hello” and the second string is “hell”.

Enter the First string
hello
Enter the Second string
hell
First string is greater than Second string

Testcase 2: The first string entered here is “hello” and the second string is “hello”.

Enter the First string
hello
Enter the Second string
hello
Both strings are EQUAL

Method 3: Using Pointers

In this approach, we will compare the two strings using pointers.

Algorithm to compare two strings using pointers:

Step 1: Start the Program
Step 2: Input both the Strings
Step 3: Declare function compare() which takes a pointer to the first character of both strings.
Step 4: If function returns 0 then both strings are equal, else strings are not equal.
Step 5: End the Program

Program/Source Code

Here is source code of the C program to accepts two strings & compare them using pointers. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C program to Compare Two Strings using pointers.
  3.  */
  4. #include <stdio.h>  
  5. int compare(char *a,char *b)  
  6. {  
  7.     int flag=0;  
  8.     while(*a!='\0' && *b!='\0')    
  9.     {  
  10.         if(*a!=*b)  
  11.         {  
  12.             flag=1;
  13.             break;
  14.         }  
  15.         a++;  
  16.         b++;  
  17.     }  
  18.     if(flag==0 && *a=='\0' && *b=='\0')
  19.     return 0;
  20.     if(*a > *b)
  21.         return 1;
  22.         else
  23.         return -1;
  24.  
  25. }    
  26. int main()  
  27. {  
  28.     char str1[30],str2[30];
  29.     printf("Enter the first string : ");  
  30.     scanf("%s",str1);  
  31.     printf("\nEnter the second string : ");  
  32.     scanf("%s",str2);  
  33.     int res=compare(str1,str2); // calling compare() function.  
  34.     if(res==0)  
  35.     printf("strings are equal");  
  36.     else
  37.     printf("strings are not equal");
  38.     return 0;  
  39. }
Program Explanation

First input the two strings. Now declare a compare function which takes a pointer to the first character of both strings. Iterate until any of the string is completely iterated or if any character differs ,stop iterating. Then compare two pointers, if the first is greater print the first string is greater, if second is greater print second string is greater else both strings are equal.

Time Complexity: O(min(n,m))
Since the loop is executed until any of the string is completely traversed, so time complexity is o(min(n,m)), where, n and m are the lengths of strings.

Space Complexity: O(1)
Since no auxiliary space is required, space complexity is O(1).

Runtime Test Cases

Testcase 1: The first string entered here is “hello” and the second string is “hell”.

Enter the First string
hello
Enter the Second string
hell
strings are not equal

Testcase 2: The first string entered here is “hello” and the second string is “hello”.

Enter the First string
hello
Enter the Second string
hello
strings are equal

To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.