From 1012ff74f3779d12282843ca910a2f97a2782cad Mon Sep 17 00:00:00 2001 From: Lovesh Dongre Date: Sun, 22 Nov 2020 23:14:40 +0530 Subject: [PATCH] ReverseWord & ReverseWordsTest (#2022) * ReverseWord & ReverseWordsTest * ReverseWord & ReverseWordsTest * fixed ReverseWords * Merge branch 'master' of https://github.com/TheAlgorithms/Java into Development --- src/main/java/com/string/ReverseWords.java | 30 +++++++++++++++++++ .../java/com/string/ReverseWordsTest.java | 15 ++++++++++ 2 files changed, 45 insertions(+) create mode 100644 src/main/java/com/string/ReverseWords.java create mode 100644 src/test/java/com/string/ReverseWordsTest.java 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