Search This Blog

Java Interview Question : Reverse a Sentence

Problem : Reverse a given sentence without using any library function. Say if the given sentence is "I am a Java Student", output must be "Student Java a am I"

Solution :  This kind of question can have another flavor which may need to print the output in exact reverse order i.e. output should be "tnedutS avaJ a ma I". This would not be difficult to implement with or without using any library function as we are not breaking the sequence of character which need to be printed. But, In case of actual question we have to read each word from end and then print it. There could be different ways to handle this problem but I have used recursion to achieve the same. Code as below.

public class ReverseSentence {

 public static void main(String[] args) {
  String s = "I am a Java Student";
  StringBuilder sb = new StringBuilder(s);
  System.out.println("Using java api : "+ sb.reverse());
  System.out.println("Output as required : " +reverseMe(s));
  

 }
 private static String reverseMe(String s) {
  System.out.println("logger ::" + s); 
  int i = s.indexOf(" ");// getting the index of space which is delimeter in case of sentence
  return i==-1 ? s : reverseMe(s.substring(i+1)) + " " + s.substring(0, i);
  
 }

}
Output :
Using java api : tnedutS avaJ a ma I
logger ::I am a Java Student
logger ::am a Java Student
logger ::a Java Student
logger ::Java Student
logger ::Student
Output as required : Student Java a am I

No comments:

Post a Comment