Reputation: 93
I am pretty new to programming/algorithm questions in Java and I can't figure out this type of sorting algorithm.
So let's say I have multiple String
elements in an array or arraylist.
"She ate 10 eclair"
"She ate 99 donuts"
"She had 20 eclair"
"She had 10 eclair"
When I sort these strings, algorithm question wants me to skip digits and sort it alphabetically first. Like this:
"She ate 99 donuts"
"She ate 10 eclair"
"She had 10 eclair"
"She had 20 eclair"
So when I use regular Collections.sort()
or compareTo()
methods, it involves digits in these strings. I am getting a hard time to build logic out of this sorting algorithm.
I have looked at the natural sorting approach but I am not sure If I am on the right track since I am very new.
So am I going to compare this per char and check if current index is a digit or not? Or am I going to convert each char to hex value and compare strings like that?
Does java offer any method that can help me out with that separation?
Any help, direction, documentation, snippet would be highly appreciated.
Regards.
Upvotes: 1
Views: 158
Reputation: 109613
For sorting often an artificial sort key is derived.
For consecutive digits to map to a same symbol one could do:
private String sortKey(String s) {
return s.replaceAll("\\d+", "0");
}
Which would replace both 10 and 99 by 0.
The regular expression:
\\d
digit+
: one or moreUpvotes: 1
Reputation: 93
Comparator
.The custom object would be composed of the following:
The custom Comparator
would only only compare using the modified string and the number(s).
Upvotes: 0
Reputation: 4809
You can provide a comparator into Collections.sort()
method which would sort regardless any digits in the input Strings:
List<String> list = ... ; //your list
Collections.sort(list, (a, b) -> a.replaceAll("[\\d]", "").compareTo(b.replaceAll("[\\d]", "")));
Upvotes: 2