C Program to Compare two String
Objective
Write a C program to compare two strings manually.
Algorithm / Approach
- Read two strings
aandb. - Start a
while(a[i] == b[i])loop that continues as long as the characters match perfectly. - Inside the loop, if we reach the end of either string (
'\0'),breakout of the loop. - Increment
i. - After the loop, check if both strings reached their null terminators simultaneously (
a[i] == '\0' && b[i] == '\0'). If yes, they are exactly the same.
main.c
#include<stdio.h>
int main( ) {
char a[100],b[100];
int i=0;
printf("Enter 1st String : ");
gets(a);
printf("Enter 2nd String : ");
gets(b);
while(a[i] == b[i]) {
if(a[i]=='\0' || b[i]=='\0') {
break;
}
i++;
}
if(a[i]=='\0' && b[i]=='\0'){
printf("Strings are same.\n");
}
else {
printf("Strings are not same.\n");
}
return 0;
}
Expected Output
Enter 1st String : C Prowess Enter 2nd String : C Prowess Strings are same.
Explanation of the Program
- This program mimics the logic of the built-in
strcmp()function. - We walk through both strings character by character. If we find a mismatch, the while loop immediately terminates. If the loop terminates naturally because both strings ended at the exact same index, it means they are identical.
Complexity
Time Complexity
O(n) - Where n is the length of the shorter string.
Space Complexity
O(1)