- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathReverseStringWordwise.java
32 lines (28 loc) · 1.07 KB
/
ReverseStringWordwise.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
// Reverse the given string word wise. That is, the last word in given string should come at 1st place, last second word at 2nd place and so on. Individual words should remain as it is.
packageString;
publicclassReverseStringWordwise {
publicstaticStringreversewordwise(Stringstr) {
Stringans = "";
intcurrentstart = str.length() - 1;
inti = str.length() - 1;
for (; i >= 0; i--) {
if (str.charAt(i) == ' ') {
intcurrentend = i + 1;
Stringsub;
sub = str.substring(currentend, currentstart + 1);
ans = ans + sub + " ";
currentstart = i - 1;
}
}
intcurrentend = i + 1;
Stringsub;
sub = str.substring(currentend, currentstart + 1);
ans = ans + sub + " ";
returnans;
}
publicstaticvoidmain(String[] args) {
Stringstr = "welcome to coding ninjas";
Stringans = reversewordwise(str);
System.out.println(ans + " ");
}
}