【问题标题】:Java sorting string based on two delimiters基于两个分隔符的Java排序字符串
【发布时间】:2017-05-29 02:55:30
【问题描述】:

我有一个如下格式的字符串 A34B56A12B56

我正在尝试根据前缀将数字排序为两个数组。 例如:

  • 数组 A:34,12
  • 阵列 B:56,56

最简单的方法是什么?

我尝试使用 String Tokenizer 类并且能够提取数字,但是无法知道前缀是什么。本质上,我只能将它们提取到一个数组中。

任何帮助将不胜感激。

谢谢!

【问题讨论】:

  • Scanner 可能很擅长这个。参见例如next(Pattern).
  • input.split("(?<=\\d)(?=\\D)")。对于返回数组中的每个元素,使用charAt(0) 获取字母(AB),使用substring(1) 获取数字。现在将数字添加到适当的List(除非您预先知道值的数量,否则不能使用数组)。
  • 这可以用有限状态机解决。
  • 谢谢安德烈亚斯。

标签: java regex string stringtokenizer


【解决方案1】:

Andreas 似乎已经提供了一个很好的答案,但我想在 Java 中练习一些正则表达式,所以我编写了以下适用于任何典型字母前缀的解决方案:(注释是内联的。)

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);
}

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

【讨论】:

    猜你喜欢
    • 2012-02-27
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多