How to to reverse String in Java Program ?

  Java Interview Q&A

Dear readers, today we read in this tutorial how each word in a string is inverted and the inverted string is displayed as the output. For example, if we input a string as “reverse the word of this string”, the output of the program would be: “Esther iht submerge seaht gnarts”.

What is reverse string in java?

Java program to reverse a string that a user inputs. The CharAt method is used to derive individual characters from a string, and we combine them in reverse order. Unfortunately, there is no built-in method for string reversal in the “string” class, but it is quite easy to create.

1. String Reverse in Java Program

The following example shows how to reverse a string after it is taken from a command line argument. The program buffers the input buffer using the string stringer string (string string) method, reverse the buffer and then converts the buffer into a string with the help of the string () method.

public class StringReverseExample{
   public static void main(String[] args) {
      String string = "abcdef";
      String reverse = new StringBuffer(string).reverse().toString();
      System.out.println("\nString before reverse: "+string);
      System.out.println("String after reverse: "+reverse);
   }
}

Output:

String before reverse:abcdef
String after reverse:fedcba

2. Java Program to reverse every word in a String using methods

In this program, we first divide the given string into substrings using the split () method. Substrings are stored in a string array of words. The program then reverses each word of the substring using the reverse for loop.

public class Example
{
   public void reverseWordInMyString(String str)
   {
	/* The split() method of String class splits
	 * a string in several strings based on the
	 * delimiter passed as an argument to it
	 */
	String[] words = str.split(" ");
	String reversedString = "";
	for (int i = 0; i < words.length; i++)
        {
           String word = words[i]; 
           String reverseWord = "";
           for (int j = word.length()-1; j >= 0; j--) 
	   {
		/* The charAt() function returns the character
		 * at the given position in a string
		 */
		reverseWord = reverseWord + word.charAt(j);
	   }
	   reversedString = reversedString + reverseWord + " ";
	}
	System.out.println(str);
	System.out.println(reversedString);
   }
   public static void main(String[] args) 
   {
	Example obj = new Example();
	obj.reverseWordInMyString("Welcome to JIQA.fastread");
	obj.reverseWordInMyString("This is Java Program Tutorial");
   }
}

Output:

Welcome to JIQA.fastread
daertsaf.AQIJ ot emocleW
This is Java Program Tutorial
sihT si na ysae avaJ margorP

Read Here Complete Java Tutorial – Click Here

LEAVE A COMMENT