Delete Word ISC Computer Science 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.util.Scanner;
class DeleteWord{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("Sentence: ");
        String s = in.nextLine().toUpperCase();
        char last = s.charAt(s.length() - 1);
        if(".?!".indexOf(last) == -1){
            System.out.println("INVALID INPUT.");
            return;
        }
        System.out.print("WORD TO BE DELETED: ");
        String w = in.nextLine().toUpperCase();
        System.out.print("WORD POSITION IN THE SENTENCE: ");
        int pos = Integer.parseInt(in.nextLine());
        String t = new String();
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if(i == 0)
                t += ch;
            else if(" .?!,".indexOf(s.charAt(i - 1)) >= 0 && ch == ' ')
                continue;
            else
                t += ch;
        }
        s = new String(t);
        int count = 0;
        String word = new String();
        t = new String();
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if(Character.isLetterOrDigit(ch))
                word += ch;
            else if(" .?!,".indexOf(ch) >= 0){
                count++;
                if(count == pos && w.equals(word)){
                    word = new String();
                    continue;
                }
                else
                    t += word + ch;
                word = new String();
            }
        }
        System.out.println(t);
    }
}

Comments

Popular posts from this blog

Encrypt Program ISC Specimen 2023 Theory

No Repeat Program ISC Computer Science 2022 Semester 2 Theory

Bank Inheritance Program ISC Specimen 2023 Theory