Monday, October 24, 2011

BlueJ Program To Remove A Specified Word From A Sentence


In this program user will enter a sentence and from the sentence a specified word has to be removed. The word will also be supplied by user. Here is the codes of the program.

 import java.io.*;
class Sentence
{
int i;
String sentence,word,str;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void disp()throws Exception
{
System.out.println("Enter the sentence:");
sentence=br.readLine();
System.out.println("Enter the word to remove:");
word=br.readLine();
i=sentence.indexOf(word);
if(i< 0)
System.out.println("The word - "+word+" does not exist in: "+sentence);
else
{
 str=sentence.substring(0,i);
 str=str+sentence.substring(i+1+word.length());
 System.out.println("Modified sentence after removing the word:"+str);
}
}
public static void main(String args[])throws Exception
{
 Sentence ob=new Sentence();
 ob.disp();
}
}

Sample input and output:

 Enter the sentence:
this is burdwan town
Enter the word to remove:
burdwan
Modified sentence after removing the word:this is town

Enter the sentence:
this is my town
Enter the word to remove:
burdwan
The word - burdwan does not exist in: this is my town

Technical analysis of this program

Function indexOf() of String class has several overloaded versions. One of the overloaded versions takes a string as argument and returns the starting location of the argument string in the invoking string. If the argument string does not exists in the invoking string, it returns zero.

If the word exists in the sentence, the program extracts the left part of the sentence by executing the statement ‘str=sentence.substring(0,i);’ and then the right part of the sentence which starts just after the specified word is extracted using the statement ‘str=str+sentence.substring(i+1+word.length());’. Here ‘i’ is the starting location of the word, ‘word.length()’ gives the length of the word. So ‘i+1+word.length()’ indicates the location just after the word.

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner