-
Notifications
You must be signed in to change notification settings - Fork 1
/
Challenge12.java
40 lines (32 loc) · 1.04 KB
/
Challenge12.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package challenge12;
import static org.junit.Assert.assertTrue;
import java.util.Set;
import org.junit.jupiter.api.Test;
/**
* reverse words in a sentence without using library method? (solution)
* Write a function, which takes a String word and returns sentence on
* which words are reversed in order e.g. if an input is "Java is best
* programming language", the output should be "language programming best is Java".
*/
public class Challenge12 {
public static String reverseWords(String input){
StringBuffer toReturn=new StringBuffer();
if(input==null || input.isEmpty()) {
return toReturn.toString();
}else {
String[] words=input.split(" ");
int wordCount=words.length;
wordCount--;
for(int i=0;i<=wordCount;i++) {
toReturn.append(words[wordCount-i]+" ");
}
}
return toReturn.toString().trim();
}
@Test
public void test() {
String returned=Challenge12.reverseWords("how hi hello");
System.out.println(returned);
assertTrue("hello hi how".equals(returned));
}
}