简体   繁体   中英

Java sorting string based on two delimiters

I have a string of the following format A34B56A12B56

And I am trying to sort the numbers into two arrays based on the prefixes. For example:

  • Array A: 34,12
  • Array B: 56,56

What is the simplest way to go about this?

I have tried to use the String Tokenizer class and I am able to extract the numbers, however there is no way of telling what the prefix was. Essentially, I can only extract them into a single array.

Any help would be appreciated.

Thanks!

Andreas seems to have provided a good answer already, but I wanted to practice some regular expressions in Java, so I wrote the following solution that works for any typical alphabetical prefix: (Comments are in-line.)

String str = "A34B56A12B56";

// pattern that captures the prefix and the suffix groups
String regexStr = "([A-z]+)([0-9]+)";
// compile the regex pattern
Pattern regexPattern = Pattern.compile(regexStr);
// create the matcher
Matcher regexMatcher = regexPattern.matcher(str);

HashMap<String, ArrayList<Long>> prefixToNumsMap = new HashMap<>();
// retrieve all matches, add to prefix bucket
while (regexMatcher.find()) {
    // get letter prefix (assuming can be more than one letter for generality)
    String prefix = regexMatcher.group(1);
    // get number
    long suffix = Long.parseLong(regexMatcher.group(2));

    // search for list in map
    ArrayList<Long> nums = prefixToNumsMap.get(prefix);
    // if prefix new, create new list with the number added, update the map
    if (nums == null) {
        nums = new ArrayList<Long>();
        nums.add(suffix);
        prefixToNumsMap.put(prefix, nums);

    } else { // otherwise add the number to the existing list
        nums.add(suffix);
    }

    System.out.println(prefixToNumsMap);
}

Output : {A=[34, 12], B=[56, 56]}

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