Skip to content

Commit 1012ff7

Browse files
authored
ReverseWord & ReverseWordsTest (TheAlgorithms#2022)
* ReverseWord & ReverseWordsTest * ReverseWord & ReverseWordsTest * fixed ReverseWords * Merge branch 'master' of https://github.com/TheAlgorithms/Java into Development
1 parent 546bc3f commit 1012ff7

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.strings;
2+
3+
public class ReverseWords {
4+
/**
5+
* Converts all of the words in this {@code String} to reversed words
6+
*
7+
* @param s the string to convert
8+
* @return the {@code String}, converted to a string with reveresed words.
9+
*/
10+
11+
public String returnReverseWords(String s) {
12+
StringBuilder sb = new StringBuilder();
13+
StringBuilder word = new StringBuilder();
14+
15+
for(int i = 0; i < s.length(); i++) {
16+
char c = s.charAt(i);
17+
if(c == ' ') {
18+
19+
sb.append(word);
20+
sb.append(" ");
21+
word.setLength(0);
22+
continue;
23+
}
24+
word.insert(0, c);
25+
}
26+
sb.append(word);
27+
28+
return sb.toString();
29+
}
30+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.string;
2+
3+
import org.junit.jupiter.api.Assertions;
4+
import org.junit.jupiter.api.Test;
5+
6+
class ReveresWordsTest {
7+
8+
@Test
9+
void testReverseWords() {
10+
ReverseWords reverseWords = new ReverseWords();
11+
Assertions.assertEquals(true, reverseWords.returnReverseWords("this is my car"), "siht si ym rac");
12+
Assertions.assertEquals(true, reverseWords.returnReverseWords("ABC 123"), "CBA 321");
13+
14+
}
15+
}

0 commit comments

Comments
 (0)