Wednesday, May 21, 2008

How to arrange words in a String alphabetically?

Similar to my last post about different way of reversing a string in java, how do you arrange words in Alphabetical order? As with my last post there are many ways one can do it. This is one of those variations. I did it as follows when I had to it for broad matching.

public class ArrangeWordsAlphabetically {

/**

* @param StringToBeOrdered

* Splits keyword at white space and arranges them alphabetically

*/

public String orderAlphabetically(String StringToBeOrdered) {

String stbr = StringToBeOrdered.toLowerCase();

String orderedString = new String();

ArrayList pList = new ArrayList();

String [] tempStr =null;

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

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

pList.add(tempStr[i]);

}

// sort list

Collections.sort(pList);

// iterate through list

for (String str : pList)

orderedString +=str + " ";

System.out.println(orderedString);

return orderedString;

}

}

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();

}

}