You are here

C program to compare two strings

C program to compare two strings using strcmp function, without strcmp function and using pointers. Function strcmp is case sensitive and returns 0 if both the strings are same.

String comparison C program

  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. int main()
  5. {
  6.    char a[100], b[100];
  7.  
  8.    printf("Enter a string\n");
  9.    gets(a);
  10.  
  11.    printf("Enter a string\n");
  12.    gets(b);
  13.  
  14.    if (strcmp(a,b) == 0)
  15.       printf("The strings are equal.\n");
  16.    else
  17.       printf("The strings are not equal.\n");
  18.  
  19.    return 0;
  20. }

Output of program:
Compare string C program output

Download Compare Strings program.

C string comparison program

We can create a function to compare two strings.

  1. #include <stdio.h>
  2.  
  3. int compare_strings(char [], char []);
  4.  
  5. int main()
  6. {
  7.    char a[1000], b[1000];
  8.  
  9.    printf("Input a string\n");
  10.    gets(a);
  11.  
  12.    printf("Input a string\n");
  13.    gets(b);
  14.  
  15.    if (compare_strings(a, b) == 0)
  16.       printf("Equal strings.\n");
  17.    else
  18.       printf("Unequal strings.\n");
  19.  
  20.    return 0;
  21. }
  22.  
  23. int compare_strings(char a[], char b[])
  24. {
  25.    int c = 0;
  26.  
  27.    while (a[c] == b[c]) {
  28.       if (a[c] == '\0' || b[c] == '\0')
  29.          break;
  30.       c++;
  31.    }
  32.    
  33.    if (a[c] == '\0' && b[c] == '\0')
  34.       return 0;
  35.    else
  36.       return -1;
  37. }

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.

  1. #include<stdio.h>
  2.  
  3. int compare_string(char*, char*);
  4.  
  5. int main()
  6. {
  7.     char first[1000], second[1000]:
  8.     int result;
  9.    
  10.     printf("Input a string\n");
  11.     gets(first);
  12.    
  13.     printf("Input a string\n");
  14.     gets(second);
  15.    
  16.     result = compare_string(first, second);
  17.    
  18.     if (result == 0)
  19.        printf("The strings are same.\n");
  20.     else
  21.        printf("The strings are different.\n");
  22.        
  23.     return 0;
  24. }
  25.  
  26. int compare_string(char *first, char *second) {
  27.    while (*first == *second) {
  28.       if (*first == '\0' || *second == '\0')
  29.          break;
  30.          
  31.       first++;
  32.       second++;
  33.    }
  34.  
  35.    if (*first == '\0' && *second == '\0')
  36.       return 0;
  37.    else
  38.       return -1;
  39. }

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