This is the second solution to to reverse each word in the given input line of strings. This program uses the core logic to reverse each string.
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Reversingeachword {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner inpStr=new Scanner(System.in);
System.out.println("Enter an input sentence");
String inpLine=inpStr.nextLine();
String resultStr ="";
//Split the input sentence into list of words with space as delimiter
List<String> words=Arrays.asList(inpLine.split("\\s"));
// Pass each word to the reverse function which returns the reversed string value
for (int i=0;i<words.size();i++) {
resultStr = resultStr + ReversingEachWord(words.get(i))+" ";
}
inpStr.close();
System.out.println("The output sentence after reversing each word is below");
System.out.println(resultStr);
}
private static String ReversingEachWord(String strVar) {
// Using basic logic of storing characters in the reverse order
String strRev= "";
for (int i=strVar.length()-1;i>=0;i--)
strRev = strRev + strVar.charAt(i);
return strRev;
}
}
Enter an input sentence
This code does not use reverse method
The output sentence after reversing each word is below
sihT edoc seod ton esu esrever dohtem

Leave a comment