diff --git a/src/main/java/com/string/ReverseWords.java b/src/main/java/com/string/ReverseWords.java new file mode 100644 index 00000000..fc9185c1 --- /dev/null +++ b/src/main/java/com/string/ReverseWords.java @@ -0,0 +1,30 @@ +package com.strings; + +public class ReverseWords { + /** + * Converts all of the words in this {@code String} to reversed words + * + * @param s the string to convert + * @return the {@code String}, converted to a string with reveresed words. + */ + + public String returnReverseWords(String s) { + StringBuilder sb = new StringBuilder(); + StringBuilder word = new StringBuilder(); + + for(int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if(c == ' ') { + + sb.append(word); + sb.append(" "); + word.setLength(0); + continue; + } + word.insert(0, c); + } + sb.append(word); + + return sb.toString(); + } +} diff --git a/src/test/java/com/string/ReverseWordsTest.java b/src/test/java/com/string/ReverseWordsTest.java new file mode 100644 index 00000000..8cfb3b5b --- /dev/null +++ b/src/test/java/com/string/ReverseWordsTest.java @@ -0,0 +1,15 @@ +package com.string; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +class ReveresWordsTest { + + @Test + void testReverseWords() { + ReverseWords reverseWords = new ReverseWords(); + Assertions.assertEquals(true, reverseWords.returnReverseWords("this is my car"), "siht si ym rac"); + Assertions.assertEquals(true, reverseWords.returnReverseWords("ABC 123"), "CBA 321"); + + } +} \ No newline at end of file