Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to Compare two String

C Code Example — String Programs

ADVERTISEMENT

C Program to Compare two String

Objective

Write a C program to compare two strings manually.

Algorithm / Approach

  1. Read two strings a and b.
  2. Start a while(a[i] == b[i]) loop that continues as long as the characters match perfectly.
  3. Inside the loop, if we reach the end of either string ('\0'), break out of the loop.
  4. Increment i.
  5. 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)
ADVERTISEMENT