Reverse Words Without Punctuation Program in Java and Python
Reverse words without punctuation program with algorithm, explanation, Java solution and simple Python solution for ISC students.
Question:
The input in this question will consist of a number of lines of English text consisting of the letters of the English alphabet, the punctuation marks apostrophe ('), full stop (.), comma (,), semicolon (;), colon (:) and white space.
Write a program to print the words of the input in reverse order without any punctuation marks other than blanks.
Note: Individual words are not reversed. Only the order of the words is reversed.
Test your program for the following data and some random data:
Algorithm:
Step 1: Start.
Step 2: Accept the number of sentences to be entered.
Step 3: Initialize an empty string text to store all the input lines together.
Step 4: Run a loop from 1 to the number of sentences.
Step 5: In every pass, accept one sentence and append it to text with a blank space after it.
Step 6: Create a StringTokenizer object using blank space and the given punctuation marks as delimiters.
Step 7: Count the number of words using countTokens().
Step 8: Run a loop exactly that many times.
Step 9: In each pass, extract one word using nextToken().
Step 10: Add the extracted word before the current reversed string so that the latest word comes first.
Step 11: After all words are processed, display the reversed words.
Step 12: Stop.
Explanation:
The program has two main tasks. First, it must read several lines of text and treat them as one continuous passage. Secondly, it must remove punctuation marks while printing the words in reverse order. To do this cleanly, all the input sentences are joined in one string named text. A blank space is added after each sentence while joining, so that the last word of one sentence and the first word of the next sentence do not accidentally combine into one word.
The most important part of the logic is the use of StringTokenizer. In this program, the delimiters are the blank space and the punctuation marks mentioned in the question. A delimiter is not treated as a word. It is only used as a separator. Therefore, when the tokenizer reads a line such as Emotions, controlled and directed, it extracts the words Emotions, controlled and directed without including the comma. This directly solves the requirement of removing punctuation marks from the output.
The number of words is stored using countTokens() before extraction begins. A for loop then runs exactly that many times, and nextToken() removes one word from the tokenizer in every iteration. This follows a predictable ISC-style structure because the loop count is known before the loop starts. Students can also dry-run it easily, as every pass of the loop extracts exactly one word and places it in the reversed output.
To reverse the order of words, the program does not reverse individual characters. Instead, every newly extracted word is placed before the previously formed output string. If the words are read as Do, not, judge, the reversed string gradually becomes Do, then not Do, then judge not Do. By the time all words are processed, the first input word has moved to the end and the last input word has moved to the beginning. This gives the required reversed word order while keeping each word unchanged.
Java Program:
/**
* The class SentMergeRev inputs multiple sentences and prints the words
* in reverse order without punctuation marks.
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
*/
import java.util.Scanner;
import java.util.StringTokenizer;
class SentMergeRev
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of sentences: ");
int n = sc.nextInt();
sc.nextLine(); // Clear the newline left after reading the integer.
String text = "";
// Accept all sentences and join them into one string.
for(int i = 1; i <= n; i++)
{
System.out.print("Enter Sentence " + i + ": ");
text = text + sc.nextLine() + " ";
}
/*
* The tokenizer separates words using spaces and punctuation marks.
* These delimiter characters are not included in the extracted words.
*/
StringTokenizer st = new StringTokenizer(text, " '.,;:!?");
int count = st.countTokens();
String reversed = "";
for(int i = 1; i <= count; i++)
{
String word = st.nextToken(); // Extract one word at a time.
// Place the new word before the previous words to reverse the order.
reversed = word + " " + reversed;
}
System.out.println("Output: " + reversed.trim());
}
}Equivalent Python Program:
n = int(input("Enter the number of sentences: "))
text = ""
# Accept all sentences and join them into one string.
for i in range(1, n + 1):
sentence = input("Enter Sentence " + str(i) + ": ")
text = text + sentence + " "
words = []
word = ""
punctuation = " '.,;:!?"
# Separate words manually using spaces and punctuation marks as delimiters.
for ch in text:
if ch not in punctuation:
word = word + ch
elif len(word) > 0:
words.append(word)
word = ""
reversed_text = ""
# Read the stored words from the end to the beginning.
for i in range(len(words) - 1, -1, -1):
reversed_text = reversed_text + words[i] + " "
print("Output:", reversed_text.strip())Output:
Leave a Reply
Your email address will not be published. Comments are reviewed before appearing publicly.