- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathReverseEachWord.java
42 lines (37 loc) · 1.38 KB
/
ReverseEachWord.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
41
42
// Aadil has been provided with a sentence in the form of a string as a function parameter. The task is to implement a function so as to print the sentence such that each word in the sentence is reversed.
// Example:
// Input Sentence: "Hello, I am Aadil!"
// The expected output will print, ",olleH I ma !lidaA".
packageString;
importjava.util.Scanner;
publicclassReverseEachWord {
publicstaticStringreversed(Stringstr) {
Stringans = "";
intcurrentWordStart = 0;
inti = 0;
for (; i < str.length() ; i++) {
if (str.charAt(i) == ' ') {
intcurrentWordEnd = i - 1;
Stringreverse = "";
for (intj = currentWordStart; j <= currentWordEnd; j++) {
reverse = str.charAt(j) + reverse ;
}
ans += reverse + " ";
currentWordStart = i + 1;
}
}
intcurrentWordEnd = i - 1;
Stringreverse = "";
for (intj = currentWordStart; j <= currentWordEnd; j++) {
reverse = str.charAt(j) + reverse;
}
ans += reverse;
returnans;
}
publicstaticvoidmain(String[] args) {
Scannersc = newScanner(System.in);
Stringstr = sc.nextLine();
Stringans = reversed(str);
System.out.println(ans);
}
}