Write a Java program to Reverse each words from a string.

 Problem: - Write a Java program to Reverse each word from a string.

Solution: - We are going to reverse the words from a string. Let's take an example. 
Input: - "java code for solution"
Output: -"avaj edoc rof noitulos".  
Java code: -

package com.codeforsolution.java.logical;

public class ReverseEachWord { public static void main(String[] args) { String input="java code for solution"; System.out.println(reverseEachWord(input)); } private static String reverseEachWord(String input) { String words[] = input.split(" "); String reverseString =""; for(int in= 0; in<=words.length-1; in++){ String revWord = ""; for(int i = words[in].length()-1; i>= 0; i--){ revWord = revWord + words[in].charAt(i); } if(in == words.length-1) reverseString=reverseString+revWord; else reverseString=reverseString+revWord+" "; } return reverseString; }
}



Output: -  avaj edoc rof noitulos 
Post a Comment (0)
Previous Post Next Post