This is the first solution to to reverse each word in the given input line of strings. This program uses the built in reverse method of StringBuffer class.
import java.util.Scanner;
import java.util.StringTokenizer;
public class ReverseEachWordInSentence {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner inpLine=new Scanner(System.in);
System.out.println("Enter an input sentence");
String sentence=inpLine.nextLine();
StringBuffer resultStr = new StringBuffer();
StringTokenizer words=new StringTokenizer(sentence);
//Process each word in a sentence, and store in an string buffer variable
while (words.hasMoreTokens()) {
StringBuffer nextWord=new StringBuffer(words.nextToken());
nextWord.reverse();
resultStr.append(nextWord+" ");
}
System.out.println("The sentence after reversing each word is = "+resultStr);
inpLine.close();
}
}
Enter an input sentence
This program demos reversing each word
The sentence after reversing each word is = sihT margorp somed gnisrever hcae drow

Leave a comment