Delete Word Program ISC 2014 Practical

Write a program to accept a sentence which may be terminated by either ‘.’, ‘?’ or ‘!’ only. Any other character may be ignored. The words may be separated by more than one blank space and are in uppercase.

Perform the following tasks:
(a) Accept the sentence and reduce all the extra blank space between two words to a single blank space.
(b) Accept a word from the user which is a part of the sentence along with its position number and delete the word and display the sentence.

Test your program for the following data and some random data:

Example 1:
INPUT: A MORNING WALK IS A IS BLESSING FOR THE WHOLE DAY.
WORD TO BE DELETED: IS
WORD POSITION IN THE SENTENCE: 6
OUTPUT: A MORNING WALK IS A BLESSING FOR THE WHOLE DAY.

Example 2:
INPUT: AS YOU SOW, SO SO YOU REAP.
WORD TO BE DELETED: SO
WORD POSITION IN THE SENTENCE: 4
OUTPUT: AS YOU SOW, SO YOU REAP.

Example 3:
INPUT: STUDY WELL##
OUTPUT: INVALID INPUT
import java.io.*;
import java.util.StringTokenizer;
class DeleteWord{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("INPUT: ");
        String s = br.readLine();
        int len = s.length();
        char last = s.charAt(len - 1);
        if(last != '.' && last != '?' && last != '!'){
            System.out.println("INVALID INPUT.");
            return;
        }
        s = s.toUpperCase();
        StringTokenizer st = new StringTokenizer(s);
        int count = st.countTokens();
        String t = new String();
        for(int i = 1; i <= count; i++)
            t += st.nextToken() + " ";
        t = t.trim();
        System.out.print("WORD TO BE DELETED: ");
        String word = br.readLine();
        word = word.toUpperCase();
        System.out.print("WORD POSITION IN THE SENTENCE: ");
        int pos = Integer.parseInt(br.readLine());
        if(pos > count || pos < 1){
            System.out.println("INVALID INPUT");
            return;
        }
        st = new StringTokenizer(t, " ?.!");
        String z = new String();
        count = st.countTokens();
        for(int i = 1; i <= count; i++){
            String w = st.nextToken();
            if(word.startsWith(w) && pos == i)
                z += w.replace(word, "");
            else
                z += w + " ";
        }
        z = z.trim();
        z += last;
        System.out.println(z);
    }
}

Leave a Reply

%d bloggers like this: