ReverseWord & ReverseWordsTest (#2022)
* ReverseWord & ReverseWordsTest * ReverseWord & ReverseWordsTest * fixed ReverseWords * Merge branch 'master' of https://github.com/TheAlgorithms/Java into Development
This commit is contained in:
parent
546bc3f5c8
commit
1012ff74f3
30
src/main/java/com/string/ReverseWords.java
Normal file
30
src/main/java/com/string/ReverseWords.java
Normal file
@ -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();
|
||||
}
|
||||
}
|
15
src/test/java/com/string/ReverseWordsTest.java
Normal file
15
src/test/java/com/string/ReverseWordsTest.java
Normal file
@ -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");
|
||||
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user