Friday, March 13, 2009

Reversing a String without using any String Functions

This was one question i got on a written round in an interview. I couldn't solve it becos all my solutions had atleast one string function involved.I got a solution from Java Cookbook by Ian.F.Darwin. But still my doubt remains if Stringbuffer and stringtokenizer areconsidered as other variants of string itself. Will this be a sensible answer for the question?
If the purpose is to reduce the duplicate String objects created during the reversal process, these solutions (using StringBuffer and StringTokenizer) should do good.

The sol goes like this:

To reverse a string by character, use the
new StringBuffer(string).reverse();

To reverse the order of words , say in a sentence string
Stack staRev= new Stack();
//Tokenize words of the long sentence string in longSt using space as default delim
StringTokenizer st = new StringTokenizer(longSt);
//Push the tokens into the stack
while(st.hasMoreTokens)
staRev.push(st.nextElement());
//Pop stack , is always in Last in First Out order. Resulting in reversing the string
while(!staRev.empty())
{
S.o.p(starRev.pop());
}

No comments:

Post a Comment