, asked
Views : 4

Write a java program to reverse each word in string?

How to reverse each word in a String using Java program? Explain with an example.

1 Answer
Anjana

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

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

Advertisements
Related Questions