ICSE Class 10 Computer Applications
Question 21 of 46
String Handling — Question 21
Back to all questions 21
Question Question 8
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
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
