Tuesday, February 2, 2010

JAVA: reverse string interview question

When you go for an interview, lot of companies ask String manipulation questions.


Some of the most common questions are:

  • Reverse words in a string (words are separated by spaces) - Most Common
  • Reverse String
  • Revers the order of words

I have written a code that performs all these functions. Hope this will help you.

/**
* Created by IntelliJ IDEA.
* User: priyank
* Date: Feb 2, 2010
*/
public class StringTest {

public static void main(String[] args) {
String str = "My name is khan";
// String result = reverseString(str);
// String result = reverseWords(str);
// String result = reverseSequence(str);
String result = iReverseSequence(str);

System.out.println(result);
}

static String reverseString(String str) {
char[] ch = str.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i=(ch.length-1);i>=0;i--) {
sb.append(ch[i]);
}
return sb.toString();
}

static String reverseWords(String str) {
String[] st = str.split("\\s");
StringBuilder sb = new StringBuilder();
for(int i=0; i < st.length;i++) {
sb.append(reverseString(st[i])+" ");
}
return sb.toString();
}

static String reverseSequence(String str) {
String[] st = str.split("\\s");
StringBuilder sb = new StringBuilder();
for(int i=(st.length-1);i>=0;i--) {
sb.append(st[i]+" ");
}
return sb.toString();
}


// Without using inbuilt java functions (for ex without using split())
// I still used substr() though
static String iReverseSequence(String str) {
String word = "";
int lastIndex = str.length();
for(int i=(str.length()-1);i>=0;i--) {
if(str.charAt(i) == ' ') {
word += str.substring(i+1,lastIndex)+" ";
lastIndex = i;
}
}
word += str.substring(0,lastIndex);
return word;
}
}

2 comments:

  1. Nice collection of String manipulation code!

    ReplyDelete
  2. Christopher LesinskiMarch 16, 2013 at 12:53 PM

    Hello,
    Thanks for the cool code ideas. I'm pretty sure that for simply reversing a string could have just been...

    public static String reverseString(String str) {
    return (new StringBuilder(str)).reverse().toString();
    }

    If we are already using a StringBuilder it has a constructor that takes a string as well as a reverse method.

    Chris Lesinski

    ReplyDelete