Here is a suggestion:

  • write a method that reverses a string:

    Copyprivate static String reverse(String s) { ... }
    
  • then in your main method, call it when necessary:

    Copyif (str.length() >= 5) str = reverse(str);
    
  • you then need to put the words back together, presumably into the reversedSentence string:

    CopyreversedSentence += str + " "; //you will have an extra space at the end
    

Side notes:

  • using a StringBuilder may prove more efficient than string concatenation for longer sentences.
  • you could put all the words back into a List<String> within the loop and call reversedSentence = String.join(" ", list) after the loop
  • reversing a string can be done in one line - you should find numerous related Q&As on stackoverflow.
Answer from assylias on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ reverse-words-given-string-java
Reverse words in a given String in Java - GeeksforGeeks
August 7, 2017 - Input: "Welcome to geeksforgeeks" ... between words and at the start or end of the string ยท Step 1: Split the string into words using a regex pattern for whitespace....
๐ŸŒ
LeetCode
leetcode.com โ€บ problems โ€บ reverse-words-in-a-string
Reverse Words in a String - LeetCode
Can you solve this real interview question? Reverse Words in a String - Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters.
๐ŸŒ
AlgoCademy
algocademy.com โ€บ link
Reverse Words in Java | AlgoCademy
Use the split() method to divide the input string into an array of words. Reverse the array of words.
๐ŸŒ
HowToDoInJava
howtodoinjava.com โ€บ home โ€บ java examples โ€บ java program to reverse words in string without using functions
Java program to reverse words in string without using functions
November 13, 2022 - Reverse each wordโ€™s characters but the position of word in string remain unchanged. Original string : how to do in java Reversed string : woh ot od ni avaj
๐ŸŒ
Reddit
reddit.com โ€บ r/programminghorror โ€บ 15 min java coding challenge - reverse words in a string on youtube. my eyes are fucking bleeding after seeing this code.
r/programminghorror on Reddit: 15 min Java Coding Challenge - Reverse Words in a String on YouTube. My eyes are fucking bleeding after seeing this code.
December 31, 2017 - For example "This is the input" becomes "sihT si eht tupni", not just a complete reversal ... I think you've got it slightly backwards; "This is the input" should become "input the is This". But if I recall correctly, the easiest way to do this is to reverse the entire string, then re-reverse each individual word.
๐ŸŒ
Medium
rameshfadatare.medium.com โ€บ java-program-to-reverse-each-word-of-a-string-0da9e728702d
Java Program to Reverse Each Word of a String | by Ramesh Fadatare | Medium
December 13, 2024 - Reassemble the String: Combine the reversed words back into a single string. Display the Result: Print the string with each word reversed. Close Resources: Close the Scanner class object automatically using the try-resource statement. // Java Program to Reverse Each Word of a String import java.util.Scanner; public class ReverseWordsInString { public static void main(String[] args) { // Step 1: Read the string from the user try (Scanner scanner = new Scanner(System.in)) { System.out.print("Enter a string: "); String input = scanner.nextLine(); // Step 2: Split the string into words String[] wo
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_howto_reverse_string.asp
Java How To Reverse a String
Java Wrapper Classes Java Generics Java Annotations Java RegEx Java Threads Java Lambda Java Advanced Sorting ... How Tos Add Two Numbers Swap Two Variables Even or Odd Number Reverse a Number Positive or Negative Square Root Area of Rectangle Celsius to Fahrenheit Sum of Digits Check Armstrong Num Random Number Count Words Count Vowels in a String Remove Vowels Count Digits in a String Reverse a String Palindrome Check Check Anagram Convert String to Array Remove Whitespace Count Character Frequency Sum of Array Elements Find Array Average Sort an Array Find Smallest Element Find Largest Element Second Largest Array Min and Max Array Merge Two Arrays Remove Duplicates Find Duplicates Shuffle an Array Factorial of a Number Fibonacci Sequence Find GCD Check Prime Number ArrayList Loop HashMap Loop Loop Through an Enum
Find elsewhere
๐ŸŒ
How to do in Java
howtodoinjava.com โ€บ home โ€บ string โ€บ reverse words in string without changing order
Reverse Words in String without Changing Order
January 8, 2023 - Loop through string array using Stream and use StringBuilder.reverse() method to reverse each word. Join all reversed words by joining the Stream elements.
๐ŸŒ
w3resource
w3resource.com โ€บ java-exercises โ€บ string โ€บ java-string-exercise-45.php
Java - Reverse words in a given string
Reverse words in String via StringBuilder: Execution time: 2670238 ns (2 ms) Reversed: yM hgih ,loohcs eht sionillI scitamehtaM dna ecneicS ,ymedacA dewohs em taht gnihtyna si elbissop dna taht er'uoy reven oot gnuoy ot kniht .gib tA ,51 I dekrow sa a retupmoc remmargorp ta eht imreF lanoitaN rotareleccA ,yrotarobaL ro .balimreF retfA ,gnitaudarg I dednetta drofnatS rof a eerged ni scimonoce dna retupmoc .ecneics Reverse words in String using Java 8 functional-style: Execution time: 143280080 ns (143 ms) Reversed: yM hgih ,loohcs eht sionillI scitamehtaM dna ecneicS ,ymedacA dewohs em taht gni
๐ŸŒ
Quora
quora.com โ€บ How-do-I-reverse-the-words-in-a-string-using-Java
How to reverse the words in a string using Java - Quora
Answer (1 of 31): There are various methods to reverse a string in Java Pseudo Code for Reverse String : 1. Convert the input string into character array by using the toCharArray() built in method of the String Class .
๐ŸŒ
Java67
java67.com โ€บ 2015 โ€บ 06 โ€บ how-to-reverse-words-in-string-java.html
How to Reverse words in String Java? [Solution] | Java67
In this code example, I have shown two ways to reverse words in a String, first one is using, Java's regular expression support to split the string into spaces and then using the reverse() method of Collections utility class.
๐ŸŒ
BeginnersBook -
beginnersbook.com โ€บ home โ€บ java examples โ€บ java program to reverse words in a string
Java Program to reverse words in a String
September 15, 2017 - public class Example { public void reverseWordInMyString(String str) { /* The split() method of String class splits * a string in several strings based on the * delimiter passed as an argument to it */ String[] words = str.split(" "); String reversedString = ""; for (int i = 0; i < words.length; i++) { String word = words[i]; String reverseWord = ""; for (int j = word.length()-1; j >= 0; j--) { /* The charAt() function returns the character * at the given position in a string */ reverseWord = reverseWord + word.charAt(j); } reversedString = reversedString + reverseWord + " "; } System.out.println(str); System.out.println(reversedString); } public static void main(String[] args) { Example obj = new Example(); obj.reverseWordInMyString("Welcome to BeginnersBook"); obj.reverseWordInMyString("This is an easy Java Program"); } }
๐ŸŒ
Java Guides
javaguides.net โ€บ 2024 โ€บ 02 โ€บ java-8-program-to-reverse-each-word-of-string.html
Java 8 Program to Reverse Each Word of String
August 14, 2024 - Output: The program prints the string with each word reversed but in the original order. Enter a string: Hello World Reversed words: olleH dlroW ยท Enter a string: Java 8 Streams Reversed words: avaJ 8 smaertS
Top answer
1 of 7
4

Edit after questions.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class Main {

   public static void main( String[] args ) {
      final String welcome = "How should we get words in string form a List?";
      final List< String > words = Arrays.asList( welcome.split( "\\s" ));
      Collections.reverse( words );
      final String rev = words.stream().collect( Collectors.joining( ", " ));
      System.out.println( "Your sentence, reversed: " + rev );
   }
}

Execution:

Your sentence, reversed: List?, a, form, string, in, words, get, we, should, How
2 of 7
3

I did suggest first reverse the whole string. Then reverse the substring between two spaces.

public class ReverseByWord {

    public static String reversePart (String in){
        // Reverses the complete string
        String reversed = "";
        for (int i=0; i<in.length(); i++){
            reversed=in.charAt(i)+reversed;
        }
        return reversed;
    }

    public static String reverseByWord (String in){
        // First reverses the complete string
        // "I am going there" becomes "ereht gniog ma I"
        // After that we just need to reverse each word.
        String reversed = reversePart(in);
        String word_reversal="";
        int last_space=-1;
        int j=0;
        while (j<in.length()){
            if (reversed.charAt(j)==' '){
                word_reversal=word_reversal+reversePart(reversed.substring(last_space+1, j));
                word_reversal=word_reversal+" ";
                last_space=j;
            }
            j++;
        }
        word_reversal=word_reversal+reversePart(reversed.substring(last_space+1, in.length()));
        return word_reversal;
    }

    public static void main(String[] args) {
        // TODO code application logic here
        System.out.println(reverseByWord("I am going there"));
    }
}
๐ŸŒ
Quora
quora.com โ€บ How-do-I-reverse-each-word-of-a-string-in-Java
How to reverse each word of a string in Java - Quora
Answer (1 of 2): Hi, We can reverse each word of a string by the help of reverse(), split() and substring() methods. By using a reverse() method of StringBuilder class, we can reverse given string.
๐ŸŒ
Scaler
scaler.com โ€บ topics โ€บ reverse-words-in-a-string
Reverse Words in a String in Data Structures - Scaler Topics
August 26, 2022 - One of the easiest ways to reverse words in a string is by splitting the string and then saving it in reverse order. This is the naive approach. We will now look at the code for this method : In Java, we have the split method, which helps us split the string.
Top answer
1 of 2
1

First of all, there is a better way to reverse the words. But lets look at your program.

I want my program to output each word on a new line.

If you want to print each word in a new line, you could either add each word to a list of words and print each word in a new line or you could just add "\n" at the end of each word.

Also notice how the letter "n" is missing from curtain and there is no space between the last two words.

This is because the endIndex starts at sentence.length()-1 and substring in Java works by extracting from startIndex to endIndex - 1 i.e. endIndex is exclusive and startIndex is inclusive. You can fix it by declaring endIndex = sentence.length() and iterate from i = sentence.length()-1 to 0.

With that the code would be:

public static void main(String[] args) {

    String sentence = new String("pay no attention to that man behind the curtain");
    String reversed = "";

    int endIndex = sentence.length();
    for(int i = sentence.length()-1; i >= 0; i--) {
        if(sentence.charAt(i) == ' ') {
            reversed += sentence.substring(i+1, endIndex) + "\n";
            endIndex = i;
        }
    }
    reversed += sentence.substring(0, endIndex);
    System.out.println(reversed);
  }

The better way is :

a) Convert your string to character array

b) Then reverse the whole character array which would become :

niatruc eht dniheb nam taht ot noitnetta on yap

c) Then reverse the letters between each space in-place.

d) You will get back the new character array that represents:

curtain the behind man that to attention no pay

and you can construct a string from the new character array.

2 of 2
1

Try this code out:

import java.util.Scanner;
 
public class ReverseString
{
 public static void main(String[] args)
 {
 System.out.println("Enter string to reverse:");
 
 Scanner read = new Scanner(System.in);
 String str = read.nextLine();
 String reverse = "";
 
 
 for(int i = str.length() - 1; i >= 0; i--)
 {
 reverse = reverse + str.charAt(i);
 }
 
 System.out.println("Reversed string is:");
 System.out.println(reverse);
 }
}