Wednesday, May 21, 2008

How do you reverse words in a String?

I haven’t posted anything in last couple of months as I have been busy with new project. I have been getting lot of requests about sample code for different posts, sorry if I haven’t replied back to you.

Thought I will share something I had to do, other day even though I got asked this question in interviews multiple times over the years.

As we all know there are many different ways of doing it with for loop, while loop, StringToeknizer or Split() etc. Since I have been doing lot of concurrency programming these days using threads, pools, blocking queues, stacks, lists etc, I thought I will try something different as follows.

public class ReverseWords {


public String ReverseStringWords(String StringToBeReversed) {


String reversedString = new String();

Stack stack = new Stack();

String [] tempStr =null;

tempStr = StringToBeReversed.split("\\s+");

for (int i = 0 ; i <>length ; i++) {

stack.push(tempStr[i]);

}

while(!stack.empty()) {

reversedString += (String) stack.pop() + " ";

}

return reversedString.toLowerCase();

}

}

No comments: