Reverse Words of a Given String in Java

In this article we are going to learn how to write a java program to reverse each and every word of a given string in java. To reverse the words of a string firstly we will use split(“\\s”) method, by using split(“\\s) we will get all the words of string sentence/phrase in an array then we will reverse each word of an array.

Example

If the input is “My Code” then the output will be “yM edoC”.

If the input is “The Code Data” then the output will be “ehT edoC ataD”.

Java Program to Reverse Words of a Given String

public class ReverseString {
        public static void main(String[] args){
            String input="The Code Data";
          ReverseString rev =new ReverseString();
            rev.reverseWordsOfString(input);
        }

        public void reverseWordsOfString(String input){
            String [] arr=input.split("\\s");
            String newString="";
            for(int i=0;i< arr.length;i++){
                newString=newString+reverse(arr[i])+" ";
            }
            System.out.println("The new String after reversing words of input string is : "+newString);
        }
        public String reverse(String s){
            String str="";
            for(int i=s.length()-1;i>=0;i--){
                str=str+s.charAt(i);
            }
            return str;
        }
    }
Java Program to Reverse Words of a Given String

Similar Java Tutorials

Leave a Comment