Skip to content

Commit ec1d80d

Browse files
Add implementation to reverse the words in a given string
1 parent 2fb03e5 commit ec1d80d

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
public class reverseWordInString {
2+
public static void main(String[] args) {
3+
String s = "Hello World";
4+
System.out.println(reverseWords(s));
5+
}
6+
7+
public static String reverseWords(String s) {
8+
String[] words = s.split(" ");
9+
StringBuilder reversedString = new StringBuilder();
10+
11+
for (int i = words.length - 1; i >= 0; i--) {
12+
reversedString.append(words[i]);
13+
if (i != 0) {
14+
reversedString.append(" ");
15+
}
16+
}
17+
18+
return reversedString.toString();
19+
}
20+
}

0 commit comments

Comments
 (0)