×

注意!页面内容来自https://www.javathinking.com/blog/reverse-a-given-sentence-in-java/,本站不储存任何内容,为了更好的阅读体验进行在线解析,若有广告出现,请及时反馈。若您觉得侵犯了您的利益,请通知我们进行删除,然后访问 原网页

How to Reverse a Sentence in Java: Step-by-Step Program Example with Input/Output

Reversing a sentence is a common string manipulation task in programmingoften asked in interviews and coding exercises. Unlike reversing individual characters (e.g."Hello" → "olleH")reversing a sentence typically means reversing the order of words while keeping each word intact (e.g."Java is fun" → "fun is Java").

In this blogwe’ll break down the process of reversing a sentence in Javaexplore different implementation methodshandle edge casesand analyze the solution’s efficiency. Whether you’re a beginner or looking to refresh your Java skillsthis guide will walk you through every step with clear examples.

Table of Contents#

  1. Understanding the Problem: What Does "Reverse a Sentence" Mean?
  2. Approach to Reverse a Sentence in Java
  3. Step-by-Step Java Program Example
  4. Handling Edge Cases
  5. Time and Space Complexity Analysis
  6. Troubleshooting Common Issues
  7. Conclusion
  8. References

1. Understanding the Problem: What Does "Reverse a Sentence" Mean?#

Before codingclarify the goal:

  • Input: A string (sentence) with words separated by spaces (e.g."I love coding").
  • Output: A new string where the order of words is reversedbut each word’s characters remain unchanged (e.g."coding love I").

Key Notes:

  • Ignore leading/trailing spaces (e.g." Hello World " → "World Hello").
  • Collapse multiple spaces between words into a single space (e.g."Java is fun" → "fun is Java").
  • Single-word inputs should return the same word (e.g."Hello" → "Hello").

2. Approach to Reverse a Sentence in Java#

The core idea is to:

  1. Split the sentence into words (using spaces as delimiters).
  2. Reverse the order of the words.
  3. Join the reversed words back into a single string with spaces.

Let’s break this down step-by-step:

Step 1: Read Input#

Firstget the input sentence from the user (or use a predefined string). We’ll use Scanner for user input.

Step 2: Split the Sentence into Words#

Use String.split(regex) to split the sentence into an array of words. To handle multiple spaces and trim leading/trailing spaces:

  • Use trim() to remove leading/trailing spaces (e.g." Hello World " → "Hello World").
  • Use split("\\s+") to split on one or more whitespace characters (handles multiple spaces between words).

Step 3: Reverse the Order of Words#

Convert the array of words into a listthen reverse the list. Alternativelymanually loop from the end of the array to the start to build the reversed sentence.

Step 4: Join the Reversed Words#

Use String.join(" "reversedWords) to combine the reversed list of words into a single string with spaces.

Step 5: Output the Result#

Print the reversed sentence.

3. Step-by-Step Java Program Example#

We’ll explore two methods to reverse a sentence:

Method 1: Using Collections.reverse() (Simplest Approach)#

This method leverages Java’s built-in Collections.reverse() to reverse the list of words.

Full Code:#

import java.util.*;
 
public class ReverseSentence {
    public static void main(String[] args) {
        // Step 1: Read input from the user
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String input = scanner.nextLine();
        scanner.close();
 
        // Step 2: Clean and split the input into words
        String trimmedInput = input.trim(); // Remove leading/trailing spaces
        if (trimmedInput.isEmpty()) { // Handle empty input
            System.out.println("Reversed sentence: ");
            return;
        }
 
        // Split into words using one or more whitespace as delimiter
        String[] words = trimmedInput.split("\\s+");
 
        // Step 3: Convert array to list and reverse
        List<String> wordList = Arrays.asList(words);
        Collections.reverse(wordList);
 
        // Step 4: Join reversed words into a sentence
        String reversedSentence = String.join(" "wordList);
 
        // Step 5: Output the result
        System.out.println("Reversed sentence: " + reversedSentence);
    }
}

Explanation:#

  • Input Handling: scanner.nextLine() reads the entire input line. trim() removes leading/trailing spaces to avoid empty words in the array.
  • Splitting Words: split("\\s+") splits the string at one or more whitespace characters (e.g."Java is fun" → ["Java""is""fun"]).
  • Reversing Words: Arrays.asList(words) converts the array to a listand Collections.reverse(wordList) reverses the list in-place (e.g.["Java""is""fun"]["fun""is""Java"]).
  • Joining Words: String.join(" "wordList) combines the reversed list into a single string with spaces.

Input/Output Examples:#

InputOutput
"Java is fun""fun is Java"
" Hello World ""World Hello"
"SingleWord""SingleWord"
"" (empty input)"" (empty output)

Method 2: Manual Reversal (Without Built-in Libraries)#

If you want to avoid Collections.reverse()you can manually loop from the end of the words array to build the reversed sentence.

Full Code:#

import java.util.Scanner;
 
public class ReverseSentenceManual {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String input = scanner.nextLine();
        scanner.close();
 
        String trimmedInput = input.trim();
        if (trimmedInput.isEmpty()) {
            System.out.println("Reversed sentence: ");
            return;
        }
 
        String[] words = trimmedInput.split("\\s+");
        StringBuilder reversedSentence = new StringBuilder();
 
        // Step 3: Loop from last word to first and append to StringBuilder
        for (int i = words.length - 1; i >= 0; i--) {
            reversedSentence.append(words[i]);
            if (i != 0) { // Add space between words (except after the last word)
                reversedSentence.append(" ");
            }
        }
 
        // Step 4 & 5: Output the result
        System.out.println("Reversed sentence: " + reversedSentence.toString());
    }
}

Explanation:#

  • Manual Reversal: Instead of using Collections.reverse()we loop from words.length - 1 (last word) to 0 (first word)appending each word to a StringBuilder.
  • Efficiency: StringBuilder is used for efficient string concatenation (avoids creating multiple intermediate strings).

4. Handling Edge Cases#

Edge cases ensure your solution is robust. Here’s how our code handles them:

Edge CaseHandling Strategy
Empty input ("")trim() converts it to an empty string; we check and return early.
Single word ("Hello")split("\\s+") returns an array with one word; reversing leaves it unchanged.
Multiple spaces ("Hi there")split("\\s+") collapses multiple spaces into a single delimiter.
Leading/trailing spaces (" Java ")trim() removes leading/trailing spaces before splitting.

5. Time and Space Complexity Analysis#

Time Complexity:#

  • Trimming: trim() runs in O(n) (n = length of input string).
  • Splitting: split("\\s+") runs in O(n) (scans the string to split into words).
  • Reversing:
    • Method 1: Collections.reverse() runs in O(m) (m = number of words).
    • Method 2: Looping through words runs in O(m).
  • Joining: String.join() or StringBuilder.append() runs in O(n) (concatenates all characters).

Overall Time Complexity: O(n) (linear timewhere n is the length of the input string).

Space Complexity:#

  • Words Array: Stores m wordsrequiring O(n) space (since total characters in words = n).
  • List/StringBuilder: Also requires O(n) space.

Overall Space Complexity: O(n) (linear space).

6. Troubleshooting Common Issues#

Issue 1: Empty Strings in the Words Array#

Problem: Using split(" ") (split on single space) instead of split("\\s+") can create empty strings if there are multiple spaces (e.g."Hello world" → ["Hello""""""world"]).
Fix: Use split("\\s+") to split on one or more whitespace characters.

Issue 2: Leading/Trailing Spaces Breaking Reversal#

Problem: Not trimming the input leads to empty words at the start/end of the array (e.g." Hi" → ["""Hi"]).
Fix: Always trim() the input before splitting.

Issue 3: Null Input#

Problem: Passing a null input causes a NullPointerException.
Fix: Add a null check:

if (input == null || input.trim().isEmpty()) { ... }

7. Conclusion#

Reversing a sentence in Java involves three core steps: splitting the sentence into wordsreversing the word orderand joining the words back. We explored two methods—using built-in Collections.reverse() for simplicity and manual looping for deeper understanding.

By handling edge cases like multiple spaces and empty inputsyou can ensure your solution is robust. The time and space complexity are linear (O(n))making the approach efficient for large strings.

8. References#

Happy coding! 🚀