Java Algorithms How to - Reverse characters in a sentence








Question

We would like to know how to reverse characters in a sentence.

Answer

import java.util.Stack;
//from  w w w.ja  v a  2 s  .c  om
public class Main {
  public static void main(String[] args) {
    String input = "This is a sentence";
    char[] charinput = input.toCharArray();
    Stack<String> stack = new Stack<String>();
    for (int i = input.length() - 1; i >= 0; i--) {
      stack.push(String.valueOf(charinput[i]));
    }
    StringBuilder StackPush = new StringBuilder();
    for (int i = 0; i < stack.size(); i++) {
      StackPush.append(stack.get(i));
    }
    System.out.println(StackPush.toString());
  }
}

The code above generates the following result.