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

Remove a Word at a Given Position

Download .java

Question

Accept an uppercase sentence ending in ., ? or !. Compress repeated spaces, then delete the specified word at the specified one-based position.

Step 1: Start and read the sentence. Step 2: Read the word to be deleted. Step 3: Read its one-based word position. Step 4: Create an array large enough to store the extracted words. Step 5: Begin scanning characters in the sentence. Step 6: Stop at the first sentence-ending punctuation mark. Step 7: Build each word by joining consecutive non-space characters. Step 8: When a space occurs, store the completed nonempty word. Step 9: Ignore all extra spaces between words. Step 10: Store the final word if necessary. Step 11: Check that the requested position is within the available words. Step 12: Check that the word at that position matches the specified word. Step 13: If either test fails, print an appropriate message. Step 14: Otherwise display all words except the selected occurrence. Step 15: Separate the displayed words using single spaces. Step 16: Stop.
Java
import java.util.*;
class DeleteWord {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine().trim();
        String target = sc.next();
        int position = sc.nextInt();
        String[] words = new String[s.length() + 1];
        int size = 0;
        String word = "";
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (ch == '.' || ch == '?' || ch == '!') {
                break;
            }
            if (ch == ' ') {
                if (word.length() > 0) {
                    words[size++] = word;
                    word = "";
                }
            } else {
                word += ch;
            }
        }
        if (word.length() > 0) {
            words[size++] = word;
        }
        if (position < 1 || position > size || !words[position - 1].equals(target)) {
            System.out.println("Word not found at position");
            return;
        }
        for (int i = 0; i < size; i++) {
            if (i != position - 1) {
                System.out.print(words[i] + " ");
            }
        }
    }
}
Input: A HEALTHY MIND OF LIVES IN A HEALTHY BODY. / OF / 4 Output: A HEALTHY MIND LIVES IN A HEALTHY BODY
← Previous Program 9 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.