Common words in two sentences

Common Words In Two Sentences


WAP to enter two sentences and print the common words in them.
/*
 * WAP to enter two senteces from the user. 
 * Print the common words in them.
 */
import java.io.*;
class CommonWords
{
public static void main (String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader (System.in));
int i,j,l1,l2,p,x,y,count=0;
String str1, str2;
char ch;

System.out.print("Enter two sentences terminated by either a '?', '.' or '!' : ");
str1 = br.readLine();
str2 = br.readLine();

l1= str1.length();
l2= str2.length();

String s1[] = new String[l1];
x=0;
p=0;
//Store all the words of the first sentence in a string array
    for(i=0;i< l1;i++)
     {
            ch = str1.charAt(i);
        if(ch == ' ' || ch == '?' || ch == '.' || ch == '!'){
            s1[x++]=str1.substring(p,i);
            p = i+1;
        }
     }
String s2[] = new String[l1];
y=0;
p=0;
     //Store all the words of the second sentence in a string array
    for(i=0;i< l2;i++)
     {
            ch = str2.charAt(i);
        if(ch == ' ' || ch == '?' || ch == '.' || ch == '!'){
            s2[y++]=str2.substring(p,i);
            p = i+1;
        }
     }

     //Now compare the words stored in two arrays
     for(i=0;i< x;i++){
        for(j=0;j< y;j++){
        //If match is found, print the word and store blank space to avoid repetition
        if(s1[i].equalsIgnoreCase(s2[j]) && !s2[j].equals(" ")){
            System.out.println(s1[i]);
            s2[j]=" ";
        }
        }
        }


}//end of main
}//end of class

Have something to say? Log in to comment on this post.

0 comments