Thursday 17 March 2016

Program to compare two strings.

//WAP in C to compare two strings
#include<stdio.h>
#include<conio.h>

void main()
{

      char string1[50],string2[50]; //used to store string
      int count1=0, count2=0, i;
      clrscr();

      printf("Enter a string: ");
      gets(string1); //input string 1

     printf("Enter another string:");
     gets(string2); // input string 2

/*Count the number of characters in string1*/
      while (string1[count1]!='\0')
                count1++;
/*Count the number of characters in string2*/

      while (string2[count2]!='\0')
                 count2++;
      i=0;

//Comparing the length of the string


      if(count1>count2)
      { 
             printf("String1 is greater than string2\n");
      } 
      else if(count1<count2)
      { 
             printf("String1 is less than string2\n");
      }

/*If the length of the strings are equal ,the string comparison starts with the first character in each string and continues with subsequent characters until the corresponding characters differ or until the end of the strings is reached.*/

      else if(count1 == count2) 
      { 
             while ( (i < count1) && (i < count2)) 
             { 
                    if (string1[i] == string2[i]) 
                    { 
                        i++; 
                        continue; 
                    }
                    else
                        printf("Strings are not equal");
              } 
        }
       getch(); // to hold the console screen
}

No comments:

Post a Comment