Programming Blog

This blog is about technical and programming questions and there solutions. I also cover programs that were asked in various interviews, it will help you to crack the coding round of various interviews

Monday, 6 November 2017

Java program to reverse words of a sentence

public class ReverseEachWord
{
    static void reverseEachWordOfString(String inputString)
    {
        String[] words = inputString.split(" ");
         
        String reverseString = "";
         
        for (int i = 0; i < words.length; i++) 
        {
            String word = words[i];
             
            String reverseWord = "";
             
            for (int j = word.length()-1; j >= 0; j--) 
            {
                reverseWord = reverseWord + word.charAt(j);
            }
             
            reverseString = reverseString + reverseWord + " ";
        }
         
        System.out.println(inputString);
         
        System.out.println(reverseString);
         
        System.out.println("-------------------------");
    }
     
    public static void main(String[] args) 
    {
        reverseEachWordOfString("Reverse This Sentence");
         
        reverseEachWordOfString("A Basic Java Program");
         
        reverseEachWordOfString("I am string not reversed");
         
        reverseEachWordOfString("Reversed");
    }
}

No comments:

Post a Comment