C Program to Compare Two Strings Word by Word Using Pointers Full Project For Beginners

  • Post author:
  • Post category:c++
  • Post comments:0 Comments

 

 

compare.c

 

 

#include <stdio.h>
int compare_strings(char [], char []);
 
int main()
{
   char a[1000], b[1000];
 
   printf("Input a string\n");
   gets(a);
 
   printf("Input a string\n");
   gets(b);
 
   if (compare_strings(a, b) == 0)
      printf("Equal strings.\n");
   else
      printf("Unequal strings.\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;
}

 

 

Using pointers

 

 

#include<stdio.h>
int compare_string(char*, char*);

int main()
{
    char first[1000], second[1000]:
    int result;
   
    printf("Input a string\n");
    gets(first);
   
    printf("Input a string\n");
    gets(second);
   
    result = compare_string(first, second);
   
    if (result == 0)
       printf("The strings are same.\n");
    else
       printf("The strings are different.\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;
}

 

Leave a Reply