You are here

C program to compare two strings

C program to compare two strings using strcmp function, without strcmp function and using pointers.

String comparison C program

#include <stdio.h>
#include <string.h>
 
int main()
{
   char a[100], b[100];
 
   printf("Enter first string\n");
   gets(a);
 
   printf("Enter second string\n");
   gets(b);
 
   if (strcmp(a,b) == 0)
      printf("Entered strings are equal.\n");
   else
      printf("Entered strings are not equal.\n");
 
   return 0;
}

Function strcmp is case sensitive and returns 0 if both strings are equal.

Download Compare Strings program.

Output of program:
Compare string C program output

C string comparison program

We can create our own function to compare two strings.

#include <stdio.h>
 
int compare_strings(char [], char []); 
 
int main()
{
   int flag;
   char a[1000], b[1000];
 
   printf("Input firsrt string\n");
   gets(a);
 
   printf("Input second string\n");
   gets(b);
 
   flag = compare_strings(a, b);
 
   if (flag == 0)
      printf("Entered strings are equal.\n");
   else
      printf("Entered strings are not equal.\n");
 
   return 0;
}
 
int compare_strings(char a[], char b[])
{
   int c = 0;
 
   while (a[c] == b[c]) {
      if (a[c] == '\0' || b[c] == '\0')
         break;
      c++;
   }
 
   if (a[c] == '\0' && b[c] == '\0')
      return 0;
   else
      return -1;
}

C program to compare two strings using pointers

We can make a function to check if two strings are similar or not by using character pointers.

#include<stdio.h>
 
int compare_string(char*, char*);
 
int main()
{
    char first[1000], second[1000], result;
 
    printf("Input first string\n");
    gets(first);
 
    printf("Input second string\n");
    gets(second);
 
    result = compare_string(first, second);
 
    if (result == 0)
       printf("Both strings are same.\n");
    else
       printf("Entered strings are not equal.\n");
 
    return 0;
}
 
int compare_string(char *first, char *second) {
   while (*first == *second) {
      if (*first == '\0' || *second == '\0')
         break;
 
      first++;
      second++;
   }
 
   if (*first == '\0' && *second == '\0')
      return 0;
   else
      return -1;
}

String comparison is a part of pattern matching e.g. when you press Ctrl+F in a web browser or text editor to search.