KnowledgeBoat Logo

Computer Applications

Write a program to input a string and print each word of the string in the reverse order.
Sample Input:
Enter a string: My name is Raman
Sample Output
yM eman si namaR

Java

Java String Handling

9 Likes

Answer

import java.util.Scanner;

public class KboatWordsReverse
{
   public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a sentence:");
        String str = in.nextLine();
             
        str += " ";
        int len = str.length();
    
        String word = "";
        int wLen = 0;
        char ch;

        for (int i = 0; i < len; i++) {
            ch = str.charAt(i);
            if (ch != ' ')   {
                word = word + ch;  
            }
            else {
                wLen = word.length();
                for(int j = wLen - 1; j >= 0; j--) {
                    System.out.print(word.charAt(j));
                }
                System.out.print(' ');
                word = "";
            }
        } 
    }
}

Output

BlueJ output of Write a program to input a string and print each word of the string in the reverse order. Sample Input: Enter a string: My name is Raman Sample Output yM eman si namaR

Answered By

3 Likes


Related Questions