Languages
[Edit]
EN

Java - reverse words in a given string

10 points
Created by:
Root-ssh
120900

1. Overview

In this post, we will take a look at how to reverse words in a given string in java.

Example 1:

String original = "Reverse words in string"; // original
String expected = "string in words Reverse"; // reversed words

Example 2:

String original = "reverse this string in java"; // original
String expected = "java in string this reverse"; // reversed words

2. Reverse words in a string

public class JavaReverseWordsInStringExample1 {

    public static void main(String[] args) {

        String original = "Reverse words in string";
        String[] split = original.split(" ");
        StringBuilder builder = new StringBuilder();

        for (int i = split.length - 1; i >= 0; i--) {
            String word = split[i];
            builder.append(word);

            if (i != 0) {
                builder.append(" ");
            }
        }
        String reversedWords = builder.toString();

        System.out.println("# original: ");
        System.out.println(original);
        System.out.println("# reversed words: ");
        System.out.println(reversedWords);
    }
}

Output:

# original: 
Reverse words in string
# reversed words: 
string in words Reverse

Java - String (popular problems)

Java - reverse words in a given string
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join