Skip to content

Commit 081f308

Browse files
Suchiqvil02
andauthored
Add ReverseWordsInString (TheAlgorithms#4456)
* return a string of the words in reverse order concatenated by a single space. Input: s = "the sky is blue" Output: "blue is sky the" * return a string of the words in reverse order concatenated by a single space. Input: s = "the sky is blue" Output: "blue is sky the" * space reduce * removed main method * added test cases * formatting fix * formatting fix * worked on pr reviews * formatting fix * private constructor added * added test case for when string contains white space * simplified method * fix issue * formatting issues fix * fixed issue * code refactor * documented method * worked on pr comments * docs: add missing space * tests: express as `ParameterizedTest` --------- Co-authored-by: Piotr Idzik <[email protected]> Co-authored-by: vil02 <[email protected]>
1 parent 064ca8f commit 081f308

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.thealgorithms.strings;
2+
3+
import java.util.Arrays;
4+
import java.util.Collections;
5+
6+
public final class ReverseWordsInString {
7+
8+
private ReverseWordsInString() {
9+
}
10+
11+
/**
12+
* @brief Reverses words in the input string
13+
* @param s the input string
14+
* @return A string created by reversing the order of the words in {@code s}
15+
*/
16+
17+
public static String reverseWordsInString(final String s) {
18+
var words = s.trim().split("\\s+");
19+
Collections.reverse(Arrays.asList(words));
20+
return String.join(" ", words);
21+
}
22+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.thealgorithms.strings;
2+
3+
import java.util.stream.Stream;
4+
import org.junit.jupiter.api.Assertions;
5+
import org.junit.jupiter.api.Test;
6+
import org.junit.jupiter.params.ParameterizedTest;
7+
import org.junit.jupiter.params.provider.Arguments;
8+
import org.junit.jupiter.params.provider.MethodSource;
9+
10+
public class ReverseWordsInStringTest {
11+
@ParameterizedTest
12+
@MethodSource("inputStream")
13+
void numberTests(String expected, String input) {
14+
Assertions.assertEquals(expected, ReverseWordsInString.reverseWordsInString(input));
15+
}
16+
17+
private static Stream<Arguments> inputStream() {
18+
return Stream.of(Arguments.of("blue is Sky", "Sky is blue"), Arguments.of("blue is Sky", "Sky \n is \t \n blue "), Arguments.of("", ""), Arguments.of("", " "), Arguments.of("", "\t"));
19+
}
20+
}

0 commit comments

Comments
 (0)