Program opened below. You can scroll through the algorithm, Java code and output.

Delete a Specified Occurrence of a Word

Download .java

Question

Accept a sentence in upper case, terminated by ., ? or !. Normalize multiple spaces to one. Then accept a word and its position occurrence and remove that occurrence from the sentence. Reject invalid sentence characters.

Step 1: Start. Step 2: Declare the variables and data structures required for the task. Step 3: Start and read the sentence. Step 4: Check that the final character is ., ? or ! and the body contains valid letters and spaces. Step 5: Initialize the counters, flags, accumulators or result structures needed by the solution. Step 6: If invalid, display INVALID INPUT and stop. Step 7: Normalize repeated spaces and split into words. Step 8: Input the word to delete and its occurrence position. Step 9: Scan the word list and count occurrences of the target word. Step 10: Skip only the requested occurrence; preserve all other words. Step 11: Join the remaining words with single spaces and append the original terminator. Step 12: Display the modified sentence and stop. Step 13: Stop.
Java
import java.util.*;
class DeleteWordOccurrence {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine().trim();
        if (!s.matches("[A-Z ]+[.?!]")) {
            System.out.println("INVALID INPUT");
            return;
        }
    char end = s.charAt(s.length() - 1);
    String body = s.substring(0, s.length() - 1).trim().replaceAll(" +", " ");
    String target = sc.nextLine().trim();
    int position = Integer.parseInt(sc.nextLine().trim());
    String[] words = body.split(" ");
    StringBuilder result = new StringBuilder();
    int count = 0;
    for (String word : words) {
        if (word.equals(target)) {
            count++;
        }
    if (!(word.equals(target) && count == position)) {
        if (result.length() > 0) {
            result.append(' ');
        }
    result.append(word);
}
}
if (count < position || position < 1) {
    System.out.println("WORD OCCURRENCE NOT FOUND");
}
else {
    System.out.println(result + String.valueOf(end));
}
}
}
Input: A MORNING WALK IS A IS BLESSING FOR THE WHOLE DAY. IS 2 Output: A MORNING WALK IS A BLESSING FOR THE WHOLE DAY.
← Previous Program 65 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.