Remove extra spaces and word

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 seperated by more than one blank space and are in UPPER CASE.

Perform the following tasks:

  1. Accept the sentence and reduce all the extra blank space between
    two words to a single blank space.
  2. Accept a word from the user which is a part of the sentece 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.

The Java implementation to remove extra spaces and word problem (asked in ISC Computer Science Practical Examination 2014) is as follows:

import java.util.*;
class RemoveWord{
    public static void main(String args[]){
        String str, word="", wordToBeRemoved, answer="";
        int position=0;
        boolean spaceFound=false, isInValidInput=false;
        Scanner sc= new Scanner(System.in);
        System.out.println("INPUT:\t");
        str=sc.nextLine();
        int spaceCount=0, length=str.length();
        char lastChar=str.charAt(length-1);
        if( !(lastChar=='.' || lastChar=='?' || lastChar=='!') ){
            System.out.print("INVALID INPUT");
        }else{
            System.out.print("WORD TO BE DELETED: ");
            wordToBeRemoved=sc.nextLine();
            System.out.print("WORD POSITION IN THE SENTENCE: ");
            position=sc.nextInt();
            char ch='.';
            for(int i=0; i < length; i++){
                ch=str.charAt(i);
                if(spaceFound && ch==' ') continue;
                if(ch==' ' || i==length-1){
                    spaceFound=true;
                    if(position-1 != spaceCount)
                        answer += (spaceCount==0?"":" ") + word;
                    spaceCount++;
                    word="";
                }else{
                    word += ch;
                    spaceFound=false;
                }

            }
            System.out.println("OUTPUT:"+answer+ch);
        }
    }
}

The point to be noted in the above Java program is the minimal use of String class functions that are expensive and internally run through the entire string in order to give results like replace(), length(), indexOf() etc. This makes the program efficient. Remember that there are marks for the choice of algorithm used and the implementation strategy.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.