Write a Java program to reverse a String is asked in many interviews, there is another version similar to it where developers are asked to write a Java program to reverse each word of a given String.
If you notice the Java program to reverse each word of a String is a combination of two programs- How to split a string in Java and how to reverse a String.
Java program to reverse each word in a String
First the passed string is split using split()
method of the
String class that returns an array having the words. Then iterate through the array and reverse each word, keep
appending each reversed word to another string.
For reversing a String there are both recursive and iterative logic, in the code both are shown.
public class ReverseWord { public static void main(String[] args) { // /Using recursive logic String str = "Reverse each word of this string"; StringBuilder sb = new StringBuilder(); // For splitting on spaces String[] strArr = str.split("\\s+"); // reversing and appending to StringBuffer for(String s : strArr) { sb.append(reverseString(s)).append(" "); } System.out.println("Original String- " + str); System.out.println("Reversed String- " + sb.toString()); // Using iterative logic str = "This is reverse program"; sb = new StringBuilder(); strArr = str.split("\\s+"); for(String s : strArr) { sb.append(reverseStringItr(s)).append(" "); } System.out.println("Original String- " + str); System.out.println("Reversed String- " + sb.toString()); } // Recursive logic to reverse a String private static String reverseString(String str) { // validation & base case if((str == null) || (str.length() <= 1)){ return str; } // recursive call return reverseString(str.substring(1)) + str.charAt(0); } // Using iteration - Non Recursive private static String reverseStringItr(String str){ // validation if((str == null) || (str.length() <= 1)){ return str; } StringBuilder sb = new StringBuilder(); for(int i = str.length() - 1; i >= 0; i--){ sb.append(str.charAt(i)); } return sb.toString(); } }
Output
Original String- Reverse each word of this string Reversed String- esreveR hcae drow fo siht gnirts Original String- This is reverse program Reversed String- sihT si esrever margorp
That's all for this topic Reverse Each Word in a String Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-
No comments:
Post a Comment