Write a java program to reverse each word in string?


StringBuffer class of the java.lang package provides reverse() method. This method returns a reverse sequence of the characters in the current String. Using this method you can reverse a string in Java.

To reverse each word in a string you need to split the string, store it in an array of strings and reverse each word using the reverse() method of the StringBuffer class.

Example

Live Demo

import java.lang.*;
public class StringBufferDemo {
   public static void main(String[] args) {
      StringBuffer buff = new StringBuffer("tutorials point");
      System.out.println("buffer = " + buff);

      // reverse characters of the buffer and prints it
      System.out.println("reverse = " + buff.reverse());

      // reverse of the buffer is equivalent to the actual buffer
      buff = new StringBuffer("malyalam");
      System.out.println("buffer = " + buff);

      // reverse characters of the buffer and prints it
      System.out.println("reverse = " + buff.reverse());
   }
}

Output

buffer = tutorials point
reverse = tniop slairotut
buffer = malyalam
reverse = malaylam

Updated on: 26-Feb-2020

485 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements