SUNDAY, 12 JULY 2026
Guide For School logo Guide For SchoolStudy Guide For Students On Java Programming
Physics | Chemistry | Mathematics
ICSE | ISC | CBSE
Guide For School logo Guide For SchoolICSE and ISC Resources

Reverse Words Without Punctuation Program in Java and Python

13 October 2013

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.

For example, consider the following input text: INPUT: Enter number of sentences: 2 Enter the sentences: This is a sample piece of text to illustrate this question if you are smart you will solve this right. OUTPUT: right this solve will you smart are you if question this illustrate to text of piece sample a is this

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:

Sample Input 1: Enter number of sentences: 1 Enter the text: Do not judge a book by its cover. Sample Output: Cover its by book a judge not do Sample Input 2: Enter number of sentences: 2 Enter the text: Emotions, controlled and directed to work, is character. By Swami Vivekananda. Sample Output: Vivekananda Swami By character is work to directed and controlled Emotions

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:

Java
/**
* 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:

Python
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:

Example 1: Enter the number of sentences: 2 Enter Sentence 1: Emotions, controlled and directed to work, is character. Enter Sentence 2: By Swami Vivekananda. Output: Vivekananda Swami By character is work to directed and controlled Emotions Example 2: Enter the number of sentences: 3 Enter Sentence 1: Did you know? Enter Sentence 2: ICSE and ISC computer is really easy. Enter Sentence 3: Thanks to guideforschool! Output: guideforschool to Thanks easy really is computer ISC and ICSE know you Did

Leave a Reply

Your email address will not be published. Comments are reviewed before appearing publicly.

Send a comment or correction

Study smarter

Everything you need for ICSE and ISC Computer

Programs, revision notes, solved papers and practical guidance—organized for quick study.

Browse all resources →