-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseWords.java
More file actions
39 lines (34 loc) · 1.32 KB
/
ReverseWords.java
File metadata and controls
39 lines (34 loc) · 1.32 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
38
39
import javax.print.DocFlavor;
public class ReverseWords {
public static String reverseWords(String s) {
//Extract word from the sentence
System.out.println(s);
System.out.println(s.length());
//remove spaces between the words its regular expression
String singleSpacedStr = s.replaceAll("\\s+", " ");
System.out.println(singleSpacedStr);
System.out.println(singleSpacedStr.length());
//Remove trailing and leading spaces in string
String trimmedString = singleSpacedStr.trim();
System.out.println(trimmedString);
System.out.println(trimmedString.length());
//convert string into string array
String words[] = trimmedString.split(" ");
System.out.println(words.length);
StringBuilder output = new StringBuilder();
System.out.print("");
//traverse the string from end to start and print the words
for (int i=words.length-1; i>=0 ;i--){
output.append(words[i]);
if (i>0)
{
output.append(" ");
}
}
return output.toString();
}
public static void main (String[] args){
String sentence = " a good example ";
System.out.print(reverseWords(sentence));
}
}