Java Program to Reverse Each Word in a Sentence

Last Updated On Saturday 15th Jan 2022

Reverse Each Word in a String Java

We can reverse each word of a string,string reverse program in java and reverse the string in java.

	import java.util.*;
import java.util.regex.Pattern;
public class Main {
  // Method to Reverse Words of a String
  public static String reverseWord(String str) {

    // Specifying the Pattern to be Searched
    Pattern pattern = Pattern.compile("\s");

    // Splitting String str with a pattern (i.e )splitting the string whenever their is whitespace and store in temp array
    String[] temp = pattern.split(str);
    String result = "";

    //Iterate over the temp array and store the string in reverse order.

    for (int i = 0; i < temp.length; i++) {
      if (i == temp.length - 1)
        result = temp[i] + result;
      else
        result = " " + temp[i] + result;
    }
    return result;
  }

  // Driver methods to test Above Method

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Input the string :");
    String str1 = sc.nextLine();
    System.out.println(reverseWord(str1));
  }
}
	

Output

	Input the string : Hello from Mars

Mars from Hello
	

Reverse a String in Java

	import java.util.*;
public class Main {

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the string");
        String input= sc.nextLine();    //input

        // convert String to character array 
        char[] str=input.toCharArray();
        for(int i=str.length-1;i>=0;i--) {
            System.out.print(str[i]);
        }
    }
}
	
	Enter the string
Hello
olleH