Can anyone tell me how to write a Java program to reverse a given sentence?
For example, if the input is:
\"This is an interview question\"
public class ReverseString {
public void reverse(String[] source) {
String dest = "";
for (int n = source.length - 1; n >= 0; n--) {
dest += source[n] + " ";
}
System.out.println(dest);
}
public static void main(String args[]) {
ReverseString rs = new ReverseString();
String[] str = "What is going on".split(" ");
rs.reverse(str);
}
}
I also give it a try: Here's a version using a stack and a scanner:
String input = "this is interview question";
Scanner sc = new Scanner(input);
Stack<String> stack = new Stack<String>();
while(sc.hasNext()) {
stack.push(sc.next());
}
StringBuilder output = new StringBuilder();
for(;;) { // forever
output.append(stack.pop());
if(stack.isEmpty()) {
break; // end loop
} else {
output.append(" ");
}
}
Bozho already gave a great Java-specific answer, but in the event you ever need to solve this problem without Java API methods:
To reverse, you can simply pop individual words onto a stack and pop them all back off when there are no words left.
(Just to be extra clear, Java does provide a Stack class, so it is possible to use this method in Java as well).
You split the string by the space then iterate over it backwards to assemble the reversed sentence.
String[] words = "This is interview question".split(" ");
String rev = "";
for(int i = words.length - 1; i >= 0 ; i--)
{
rev += words[i] + " ";
}
// rev = "question interview is This "
// can also use StringBuilder:
StringBuilder revb = new StringBuilder();
for(int i = words.length - 1; i >= 0 ; i--)
{
revb.append(words[i]);
revb.append(" ");
}
// revb.toString() = "question interview is This "
No one has mentioned a vanilla Java 8 based solution yet, which is the same as Bozho's, but without any third-party libraries. So here it is:
String input = "This is interview question";
List<String> list = Arrays.asList(input.split(" "));
Collections.reverse(list);
System.out.println(list.stream().collect(Collectors.joining(" ")));
Before StringTokenizer was declared legacy, many used StringTokenizer for this. Thought I would just leave it here.
String sentence = "This is interview question";
String reversed = "";
StringTokenizer tokens = new StringTokenizer(sentence);
while (tokens.hasMoreTokens()) { // Loop through each token
reversed = tokens.nextToken() + ' ' + reversed; //add to start
}
System.out.println(reversed.trim());