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"
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(); } }
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); } }
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(); } }
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!")); } }