Program opened below. You can scroll through the algorithm, Java code and output.
Program 65
Delete a Specified Occurrence of a Word
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.
Algorithm
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 program
Javaimport 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));
}
}
}Sample output
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.