Reversed Words in Java

The challenge

Complete the solution so that it reverses all of the words within the string passed in.

Example:

ReverseWords.reverseWords("The greatest victory is that which requires no battle"); // should return "battle no requires which that is victory greatest The"
Code language: Java (java)

The solution in Java code

Option 1 (using StringBuilder):

public class ReverseWords{ public static String reverseWords(String str){ String[] words = str.split(" "); StringBuilder sb = new StringBuilder(); for (int i=words.length-1; i>=0; i--) { sb.append(words[i]).append(" "); } return sb.toString().trim(); } }
Code language: Java (java)

Option 2 (using Arrays):

import java.util.*; public class ReverseWords{ public static String reverseWords(String str){ List Words = Arrays.asList(str.split(" ")); Collections.reverse(Words); return String.join(" ", Words); } }
Code language: Java (java)

Option 3 (using streams):

import java.util.Arrays; public class ReverseWords{ public static String reverseWords(String str){ return Arrays.stream(str.split(" ")).reduce((x, y) -> y+" "+x).get(); } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void testSomething() { assertEquals("eating like I", ReverseWords.reverseWords("I like eating")); assertEquals("flying like I", ReverseWords.reverseWords("I like flying")); assertEquals("nice is world The", ReverseWords.reverseWords("The world is nice")); assertEquals("nice so not is world The", ReverseWords.reverseWords("The world is not so nice")); assertEquals("beatiful is Life", ReverseWords.reverseWords("Life is beatiful")); assertEquals("won! we hello Hello", ReverseWords.reverseWords("Hello hello we won!")); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments