Wednesday 14 March 2018

Counting common characters in two strings

This C program reads two strings s1 and s2 and outputs the number of characters that are common in both strings.
For example, if the input strings are
hello
welcome

output will be
3

Explanation
The common characters are e, l, o
Also a boundary condition is included which requires the length of the two strings must be between 3 and 100.

PROGRAM

#include<stdio.h>
#include <stdlib.h>

int main()
{
  char s1[100],s2[100],d[100];
  int i=0,j=0,n=0,m=0,count=0,k;

  printf("Enter two strings\n");
  scanf("%s%s",s1,s2);
  while(s1[i++] != '\0')
    n=i;
  while(s2[j++] != '\0')
    m=j;
    j=0;
  if ((n >= 3 && n<100) && (m >=3 && m < 100))
  {
          for(i=0;i<n;i++)

         {
              for(k=0;k<=j;k++)

             {
                  if(s1[i] == d[k])
                      break;
              }
              if(k>j)
                      d[j++]=s1[i];
         }
          d[j]='\0';

    for(i=0;i<=j-1;i++)
    {
          for(k=0;k<m;k++)
          {
             if(d[i] == s2[k])
             {
                 count++;

                 break;
             }
        }
    }   
 
  printf("\n%d",count);
  }

return 0;    
}

OUTPUT
Enter two strings
india
china
3

No comments:

Post a Comment