Reputation: 13
So if I have a string array such as:
array = { "Carol", "`-=[]\;',.//uF18*-+~!@#$*"};
how would I sort it so punctuation symbols are first in the re-assortment? Using Arrays.sort(array) will put these after any strings with alphabetical beginnings. the goal is for it to be:
array = {"`-=[]\;',.//uF18*-+~!@#$*", "Carol"}
after sorting.
Upvotes: 1
Views: 307
Reputation: 10931
This sounds like collation, which is typically based on a custom character sequence. E.g. a RuleBasedCollator
will let you define how different chars relate to each other:
Collator collator = new RuleBasedCollator("< '`','-','=' < A,B,C");
String[] array = { "Carol", "`-=[]\\;',.//uF18*-+~!@#$*"};
Arrays.sort(array, collator);
That's been kept short for readability, but clearly you'll need to work through more characters in those rules. There's usually no need to go too far though - any characters you leave out just revert to their normal sequence, after the ones in the rules. And note punctuation chars tend to need to be quoted.
RuleBasedCollator
does have quite a bit more going on in these rules though. For example it can handle multi-letter grouping before sorting, e.g. "< c < ch < d"
for Spanish. If in doubt, take a look at the Javadocs.
Upvotes: 2