Insert Word in Sentence Program in Java | ISC Computer Science Paper 2

Write a program to accept a sentence which may be terminated by either ‘.’ or ‘?’ 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 a sentence and remove all the extra blank space between two words to a single blank space.
(b) Accept any word from the user along with its position and insert the word in the given position. The position is calculated by place value of each word where first word is in position 1, second word in position 2 and so on.
(c) Display the modified sentence.

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

Example 2
INPUT:
AS YOU SOW, SO YOU REAP!
WORD TO BE INSERTED: SHALL
WORD POSITION IN THE SENTENCE: 5
OUTPUT: AS YOU SOW, SO SHALL YOU REAP!

Example 3
INPUT: BETTER LATE THAN NEVER#
OUTPUT: INVALID SENTENCE

import java.util.Scanner;
class InsertWord{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("SENTENCE: ");
        String s = in.nextLine().trim().toUpperCase();
        char last = s.charAt(s.length() - 1);
        if(".?!".indexOf(last) == -1){
            System.out.println("INVALID SENTENCE");
            return;
        }
        System.out.print("WORD TO BE INSERTED: ");
        String word = in.nextLine().trim().toUpperCase();
        System.out.print("WORD POSITION IN THE SENTENCE: ");
        int pos = Integer.parseInt(in.nextLine());
        int len = s.length();
        while(s.indexOf("  ") > 0)
            s = s.replace("  ", " ");
        int count = 1;
        if(pos <= countWords(s)){
            for(int i = 0; i < len; i++){
                char ch = s.charAt(i);
                if(count == pos){
                    s = s.substring(0, i) + word + " " + s.substring(i);
                    break;
                }
                else if(" .?!".indexOf(ch) >= 0)
                    count++;
            }
        }
        else
            s = s.substring(0, len - 1) + " " + word + s.charAt(len - 1);
        System.out.println(s);
    }
    public static int countWords(String s){
        int c = 0;
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if(" .?!".indexOf(ch) >= 0)
                c++;
        }
        return c;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *