ISC practical papers › ISC 2014 › Question 3
Remove a word from a string
ISC 2014 Computer Science Practical, Question 3 · Strings
The question
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:
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.
Question: ISC 2014 Computer Science Paper 2 (Practical), Question 3, set by the Council for the Indian School Certificate Examinations (CISCE). Solution and video: Vinay Singh.
Java solution
import java.util.*;
class Sentence{
private String source,wordList[], answer;
private char terminator;
public Sentence(String source){
this.source = source;
}
public boolean isValid(){
terminator = source.charAt(source.length()-1);
return (new String(".?!")).indexOf(terminator)>-1;
}
public void delete(String wordToBeDeleted, int position){
answer="";
wordList = source.split(" ");
System.out.println(Arrays.toString(wordList));
int wordCount=0;
for(String word: wordList){
if(word.length()==0) continue;
wordCount++;
if(wordCount==position && word.equals(wordToBeDeleted)) continue;
answer+=word+" ";
}
}
public String toString(){
return answer.trim();
}
}
class ISC2014Q3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("INPUT:\t");
String source = in.nextLine();
Sentence objSentence = new Sentence(source);
if(objSentence.isValid()){
System.out.print("WORD TO BE DELETED: ");
String wordToBeDeleted = in.nextLine();
System.out.print("WORD POSITION IN THE SENTENCE: ");
int position = in.nextInt();
objSentence.delete(wordToBeDeleted,position);
System.out.println("OUTPUT:\t"+objSentence);
}else{
System.out.println("OUTPUT:\tINVALID INPUT.");
}
in.close();
}
}
All these solutions in one free book
Pragmatic Solutions to ISC Computer Science Practical Problems collects every program from 2004 to 2021 in a 202-page PDF.