forked from avinashbest/java-coding-ninjas
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseEachWord.java
More file actions
37 lines (35 loc) · 1.26 KB
/
ReverseEachWord.java
File metadata and controls
37 lines (35 loc) · 1.26 KB
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
package strings;
public class ReverseEachWord {
public static String reverseEachWord(String str) {
String answer = "";
int currentWordStart = 0;
int i = 0;
for (; i < str.length(); i++) {
if (str.charAt(i) == ' ') {
// Reverse Current Word
int currentWordEnd = i - 1;
String reversedWord = "";
for (int j = currentWordStart; j <= currentWordEnd; j++) {
reversedWord = str.charAt(j) + reversedWord;
}
// Add it final string(answer)
answer += reversedWord + " ";
currentWordStart = currentWordStart + i + 1;
}
}
// for the last word there is no space
int currentWordEnd = i - 1;
String reversedWord = "";
for (int j = currentWordStart; j <= currentWordEnd; j++) {
reversedWord = str.charAt(j) + reversedWord;
}
// Add it final string(answer)
answer += reversedWord + " ";
// returning the reversed each word which is stored in the answer
return answer;
}
public static void main(String[] args) {
String str = "abc def ghi";
System.out.println(reverseEachWord(str));
}
}