Difficulty sorting text from substrings using java.util.*
Hi All,
I am confused with which java.util.* to use when trying to sort some substrings from a long string.
E.g. String myString = "M09000|Q00009|R01000|T7X100"
What I like to get out is this string below:
String sortedstring = "T7X100|R01000|Q00009|M09000"
In other word, I would like to do the following steps according to my understanding:
( i ) Convert myString to an array (myArray), possibly have to strip out the "|" with space.
( ii ) Sort out myArray in reverse order before before converting back to String (myString).
It is certainly possibly to write my own methods to do this but wanted to use Java's abundance of sorting tools, if only I know which one to use.
I have read through many of Java doc on utilities such as java.util.Comparable, java.util.Arrays.sort or java.util.Arrays.reverse including the following example without success:
List list = Arrays.asList(myString);
Collections.sort(list); or Collections.reverse(list);
Any assistance would be appreciated.
Thanks,
Henry
String's split() method will produce an array of strings, splitting your original
string every time it sees a "|". Be careful because split() takes a parameter
which is a regex pattern. (There is a link to how regex patterns work in the
split() API documentation).
You don't really have to sort this array. To print it backwards just use a for-loop
starting at the end and working backwards adding a "|" as required.
Try
String list[] = myString.split("\|");
Arrays.sort(list);
StringBuffer sb = new StringBuffer();
for (int i=0; i<list.length; i++){
if (i>0)
sb.append("|");
sb.append(list[i]);
}
return sb.toString();
but using String.split has a high performance cost becouse it uses reguler expressions. If you use a StringTokenizer to split the string that will be much faster but your code will get little longer.
LRMKa at 2007-7-7 15:45:37 >

String[] parts = myString.split("\\|");
int i = parts.length - 1;
if (i == 0) {
return parts[0];
}
StringBuilder sb = new StringBuilder(parts[i--]);
for (; i >= 0; i--){
sb.append("|").append(parts[i]);
}
return sb.toString();
Warning people about a performance penalty from using split() over StringTokenizer is an example of premature optimization.
For economy of code I like
public static String reverse(String line)
{
int index = line.indexOf("|");
return (index >= 0) ? reverse(line.substring(index+1)) + "|" + line.substring(0, index): line;
}