Monday, April 4, 2016

C program to compare two strings

This c program compares two strings using strcmp, without strcmp and using pointers. For comparing strings without using library function see another code below.

C program to compare two strings using strcmp

#include <stdio.h>
#include <string.h>
 
int main()
{
   char a[100], b[100];
 
   printf("Enter the first string\n");
   gets(a);
 
   printf("Enter the 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.
Output of program:
Compare String program

C program to compare two strings without using strcmp

Here we create our own function to compare strings.
#include <stdio.h>
 
int compare_strings(char [], char []); 
 
int main()
{
   int flag;
   char a[1000], b[1000];
 
   printf("Input first 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

In this method we will make our own function to perform string comparison, we will use character pointers in our function to manipulate string.
#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;
}

0 comments:

Post a Comment