icse-promo

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 separated by more than one blank space and are in uppercase.
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
				
			

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner;

public class DeleteWordFromPosition
{
    public static void main(String args[])
    {
        int i=0,count=1,len=0,pos=0;
        char ch=' ',last=' ';
        String sen="",newsen="",wd="",wd1="";
        Scanner sc=new Scanner(System.in);
        System.out.print("ENTER A SENTENCE: ");
        sen =sc.nextLine();
        len = sen.length();
        last = sen.charAt(len - 1);
        if(last != '.' && last != '?' && last != '!')
        {
            System.out.println("INVALID INPUT.");
            return;
        }
        sen = sen.toUpperCase();

        System.out.print("WORD TO BE DELETED: ");
        wd = sc.next();
        wd = wd.toUpperCase();
        System.out.print("WORD POSITION IN THE SENTENCE: ");
        pos = sc.nextInt();
        for(i=0;i< len;i++)
        {
            ch=sen.charAt(i);
            if(ch==' '||ch=='.'||ch=='?'||ch=='!')
            {
                if(wd1.equals(wd)==true && (count)==pos)
                {
                    /*do nothing*/
                }
                else
                {
                    newsen=newsen+wd1+ch;
                }
                wd1="";
                count++;
            }
            else
            {
                wd1=wd1+ch;   
            }
        }
        System.out.println("NEW SENTENCE:"+newsen);
    }
}

				
			

Coding Store

Leave a Reply

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