Merge several sentences

Merge Several Sentences


Enter n sentences and merge them to form a single sentence, where n <= 10. The merged sentence should not have duplicate words and must only consist of letters and blank spaces. Any other character should be removed.
 /*
 * Enter n sentences and merge them to form a single sentence, 
 * where n <= 10. The merged sentence should not have duplicate words and must
 * only consist of letters and blank spaces. Any other character
 * should be removed.
 */
import java.io.*;
class MergeSentence
{
public static void main (String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader (System.in));

int n,i,j,k,p,x,l,now;
String ms;
char ch,t;

System.out.println("Enter the no of sentences (upto 10): ");
n = Integer.parseInt(br.readLine());
if(n<=10){

//String array to store the sentences
String str[] = new String[n];

//counter to store number of words
now=0;

System.out.println("Enter the "+n+" sentences: ");
    for(i=0;i< n;i++)
    {
        str[i]=br.readLine();

        //This loop is used to count the number of words in all the sentences.
        //The counter is then used to initialize the array that stores all the words
        for(j=0;j< str[i].length();j++){
            ch = str[i].charAt(j);
            if(ch == ' ' || ch == '?' || ch == '.' || ch == '!'){
                now++;
            }
        }
    }

    //String array to store number of words
    String words[] = new String[now];


    x=0;
    for(i=0;i< n;i++){
        l=str[i].length();
        p=0;
        for(j=0;j< l;j++){
            ch = str[i].charAt(j);
            ms="";
            if(ch == ' ' || ch == '?' || ch == '.' || ch == '!'){
                //Loop to access the word
                for(k=p;k< j;k++){
                        t = str[i].charAt(k);
                        //Only add letters to the merged string
                        if((t >= 'A' && t<='Z') || (t>='a' && t<='z'))
                            ms = ms + t;
                    }
               //Store the words in string array
               words[x++] = ms;
               p = j+1;
            }
        }
    }
    //Now remove duplicate words from the string array
    for(i=0;i< x;i++){
    for(j=i+1;j< x;j++){
        if(words[i].equalsIgnoreCase(words[j])){
            for(k=j;k< x-1;k++)
                words[k] = words[k+1];
            j--; // Decrement loop counter to cater to successive duplicates
            x--;
        }
     }
    }
    for(i=0;i< x;i++){
    System.out.print(words[i]+" ");
}
}else{
System.out.println("Invalid value!");
}

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

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

0 comments