-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay8.java
More file actions
20 lines (19 loc) · 709 Bytes
/
Copy pathDay8.java
File metadata and controls
20 lines (19 loc) · 709 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class ReverseWordsInString {
public static String reverseWords(String s) {
s = s.trim();
String[] words = s.split("\\s+");
StringBuilder sb = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
sb.append(words[i]);
if (i != 0) sb.append(" ");
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(reverseWords("the sky is blue"));
System.out.println(reverseWords(" hello world "));
System.out.println(reverseWords("a good example"));
System.out.println(reverseWords(" "));
System.out.println(reverseWords("word"));
}
}