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;

}

}

1 comment:

Anonymous said...

Nice brief and this enter helped me alot in my college assignement. Say thank you you seeking your information.