Finding same characters in any two string

Asked By 0 points N/A Posted on -
qa-featured

Hello,

How to find similar characters in any two string arrays. 

Such as from:

Char str1 [15] = "Programming";

char srt2[15]= "scripting";

SHARE
Answered By 0 points N/A #160441

Finding same characters in any two string

qa-featured

Use nested for loops for finding similar characters, such as each element of first string should compare to all characters of 2nd, if same then copy it into another array. But keep in mind while saving in another array you should check whether the array contains the same element already or not.

Sample code is…

  char str1[20]="programming";

  char str2[15]="scripting";
  int i,j;
   char same[20];
   bool check=true;int k=-1;
  int  n1=strlen(str1);
   int n2=strlen(str2);  
    for(i=0;i<n1;i++)
    {check = true;
      for(j=0;j<n2;j++)
      {
        if(str1[i]==str2[j])
          {
                                  
          for(int s=0;s<=k;s++)
          {if(str1[i]==same[s])   // if already in same[s] then don't save again
          check=false;
          }
         if(check==true) // check true , when then was no element already found in same []
         {
                        same[++k]=str1[i];}
          
          }
      }
    }
    cout<<endl;
    for(int s=0;s<=k;s++)
    {
            cout<<same[s];      // print similar elements
            cout<<" ";
            }
            cout<<endl;

Related Questions