How to reverse each word of string?

How to reverse each word of string.

Problem Statement:

  1. I have a string with multiple words. I want to reverse each word of this string.
  2. Reverse each word of string.
 Source Code:
 package com;

public class Test {
	public static void main(String[] args) {
		String str1 = "Java and J2EE Technology Servlet";
		String str2 = "Anupam Kumar Dwivedi";

		System.out.println("Reverse String str1 :: " + reverseString(str1));
		System.out.println("Reverse String str2 :: " + reverseString(str2));
	}

	static String reverseString(String in) {
		String[] str = in.split(" ");

		String outStr = "";

		for (int i = 0; i < str.length; i++) { String tempStr = str[i]; String rStr = ""; for (int j = tempStr.length() - 1; j >= 0; j--) {
				rStr = rStr + tempStr.charAt(j);
			}

			outStr = outStr + rStr + " ";
		}
		return outStr;

	}
}

Output:

Reverse String str1 :: avaJ dna EE2J ygolonhceT telvreS 
Reverse String str2 :: mapunA ramuK ideviwD 


10article.com Tutorials

10article.com Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *