Tuesday, October 20, 2020

BlueJ Program To Replace Particular Word From A Sentence With Another

 In this BlueJ Program, take a sentence and two words. First word to be replaced by second word (if present) and construct a new sentence

e,g: Input: Durga Puja is a great festival
1st word: is
2nd word: was
Output: Durga Puja was a great festival

import java.util.*;
class Frequency
{
  int i;
  String str,s,word,replace,str1="";
Scanner sc=new Scanner(System.in);
public void take()
{
     System.out.print("\nEnter the sentence:");
     str=sc.nextLine();
     str=str+" ";
     System.out.print("\nEnter the word to be replaced:");
     word=sc.nextLine();
     System.out.print("\nEnter the word with which to replace:");
     replace=sc.nextLine();
     while(true)
     {
          i=str.indexOf(' ');
          if(i<0)
          break;
          s=str.substring(0,i);
          str=str.substring(i+1);
          if(s.equals(word))
          str1=str1+ " " + replace;
          else
          str1=str1+ " " + s;
      }
      str1=str1.trim();
      System.out.print("\nModified Sentence is: "+str1);
    }
    public static void main(String args[])
    {
         Frequency ob=new Frequency();
         ob.take();
    }

}

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner