简体   繁体   中英

Sorting strings alphabetically that have digits in them

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.

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]", "")));

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
  • postfix operator + : one or more
  1. Convert the list of Strings to a list of custom objects. Each of these custom objects would contain a reference to the corresponding original string.
  2. Sort the second list using a custom Comparator .
  3. Convert the second list back to a list of strings (by extracting the original strings).

The custom object would be composed of the following:

  • reference to original string
  • modified string (eg numbers replaced with “%”)
  • the number (or a list of numbers)

The custom Comparator would only only compare using the modified string and the number(s).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM