July 13, 2016

How to reverse a String in Java?

How to reverse a String is one of the common interview question. In Java, we can do this in a couple of ways:
  • Reverse a String using CharAt Method
  • String reverse using String Buffer/String Builder Approach
  • Reverse a String using Reverse Iterative Approach
  • String reverse using Recursion
GIT URL: How to reverse a String in Java

Reverse each word in String
Recently I applied for a Senior Java Developer position in a small IT company in Mumbai. In the first round of interview they asked me solve a couple of puzzles and algorithms. One of the questions that was asked is to write a Java Program to reverse each word in String.

public String reverseEachWord(String str){
  //get all words in an array
  String words[]=str.split("\\s");  
  String reverseWord="";
  StringBuilder sb;
  
  for(String word:words){  
    sb=new StringBuilder(word);  
    sb.reverse();  
    reverseWord+=sb.toString()+" ";  
  }  
  return reverseWord.trim();
}
-K Himaanshu Shuklaa..

No comments:

Post a Comment