Program : Reverse each word of String
Write a program that takes a string input from the user and then reverse each word of the of the line as entered by the user.Expected input : "This is a very good blog"
Expected output : "sihT si a yrev doog golb"
import java.io.*;
public class ReverseString{
public static void main(String args[]){
ReverseString obj = new ReverseString();
String inputString = obj.getStringFromUser();
String outputString = "";
String aux = "";
for(int itr=0;itr<inputString.length();itr++){
// reverse the words if a whitespace occurs.
if(inputString.charAt(itr) == ' '){
outputString += reverseString(aux) + " ";
aux = "";
}
else{ // extract the word from the string
aux += inputString.charAt(itr);
}
}
// reverse the last word of the string
outputString += reverseString(aux);
System.out.println(outputString);
}
public static String reverseString(String str){
String aux = "";
for(int itr = str.length()-1;itr>=0;itr--){
aux += str.charAt(itr);
}
return aux;
}
public String getStringFromUser(){
try{
System.out.println("Enter String to be reversed");
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
return br.readLine();
}
catch(Exception e){e.printStackTrace();}
return "ekansh";
}
}
Output of the program :
Enter String to be reversed
This is a very good blog
sihT si a yrev doog golb
Comments
Post a Comment