0
Sponsored Links


Ad by Google
One of the popular interview question, and most of the time interviewer asked this question while first round of technical interview specially for freshers. Interviewer ask you to check your logical ability, once you provide the solution for this question, interview start asking you to provide some other way to reversing a string and start discussing why this approach is good and why other not and so on..
Although, I had already shared a list of written Java interview questions here and in this article going to show you how to reverse a string with multiple options.

Reverse a String
Example,
Input: gnirts a esrever ot woh
Expected Output: how to reverse a string

Input: esuekamavaj
Expected Output: javamakeuse

package com.javamakeuse.poc;

/**
 * 
 * @author javamakeuse
 *
 */
public class ReverseString {

 // using built in function
 public static String reverseString(String str) {
  return new StringBuilder(str).reverse().toString();
 }

 // using character
 public static String reverseString2(String str) {
  String result = "";
  for (int i = str.length() - 1; i >= 0; i--) {
   result = result + str.charAt(i);
  }
  return result;
 }

 // using recursion
 public static String reverseString3(String str) {
  if (str.length() == 0)
   return "";
  return str.charAt(str.length() - 1) + reverseString3(str.substring(0, str.length() - 1));
 }

 public static void main(String[] args) {
  System.out.println(reverseString("esuekamavaj"));
  System.out.println(reverseString2("esuekamavaj"));
  System.out.println(reverseString2("esuekamavaj"));

 }
}
OUTPUT:
how to reverse a string
javamakeuse
javamakeuse

Sponsored Links

0 comments:

Post a Comment