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
public class StringReverse {
//Reverse a String using CharAt Method
public String reverStringCharAt(String str) {
String reverseStr="";
for(int i=str.length()-1;i>=0;i--)
reverseStr=reverseStr+str.charAt(i);
return reverseStr;
}
// Reverse a String using String Builder
public String reverStringBuilder(String str) {
return new StringBuilder(str)
.reverse().toString();
}
// Reverse a String using String Buffer
public String reverStringBuffer(String str) {
return new StringBuffer(str)
.reverse().toString();
}
//Reverse a String using Reverse Iteration
public String reverStringItr(String str) {
char c[]=str.toCharArray();
String reverseStr="";
//For loop to reverse a string
for(int i=c.length-1;i>=0;i--)
reverseStr+=c[i];
return reverseStr;
}
//Reverse a String using Recursion
public String reverStringRec(String str) {
if(str.length() == 0)
return " ";
return str.charAt(str.length()-1) +
reverStringRec(str.substring(0,str.length()-1));
}
}

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