Java Data Type How to - Reverse each word in a string without altering their position








Question

We would like to know how to reverse each word in a string without altering their position.

Answer

/*  w w  w . j a v  a  2s  .  c om*/
public class Main {
  public static void main(String args[]) {
    String input = "this is a test";
    String[] words = input.split(" ");
    String reverse = "";
    for (int i = 0; i < words.length; i++) {
      for (int j = words[i].length() - 1; j >= 0; j--) {
        reverse += words[i].charAt(j);
      }
      System.out.print(reverse + " ");
      reverse = "";
    }
  }
}