我试图将一个字符串拆分为一个字符串列表,该列表根据是否可以强制转换字符而更改。换句话说,我想将字符串分成不同的数字和字母组。为了增加乐趣,我还尝试修剪每组数字中的前导0。考虑以下示例。

假设您得到"aoeu01234stnh0987"作为输入。我想要的输出是["aoeu", "1234", "stnh", "987"]

我在下面做了一个工作示例,但是它有些长且令人困惑。似乎必须有一个更好,更简洁的方法来实现这一目标。

private static List<String> fragmentString(String string) {
    char[] charArr = string.toCharArray();
    StringBuilder tempStr = new StringBuilder();
    StringBuilder tempInt = new StringBuilder();
    List<String> tempList = new ArrayList<>();
    boolean wasPrevNum = false;

    for (char c : charArr) {
        boolean isNum = Character.isDigit(c);
        if (isNum) {
            tempInt.append(c);
            if (!wasPrevNum) {
                wasPrevNum = true;
                tempList.add(tempStr.toString());
                tempStr = new StringBuilder();
            }
        } else {
            tempStr.append(c);
            if(wasPrevNum) {
                while (tempInt.charAt(0) == '0') tempInt.deleteCharAt(0);
                tempList.add(tempInt.toString());
                tempInt = new StringBuilder();
                wasPrevNum = false;
            }
        }
    }
    if(tempInt.length() > 0) while (tempInt.charAt(0) == '0') tempInt.deleteCharAt(0);
    tempList.add(wasPrevNum ? tempInt.toString() : tempStr.toString());
    return tempList;
}

我看到了有关使用split()方法的这个帖子,但是该解决方案仅适用于非常特殊的情况,不适用于此情况。 split()方法是解决此问题的第一件事,但是我无法弄清楚正则表达式,现在我在质疑使用split()是否可能。

分析解答

一个非常简单的解决方案可以使用正则表达式。正则表达式\p{L}+|[0-9]+表示字母序列或数字序列,可用于查找子字符串。然后,尝试解析找到的子字符串。如果它是整数,则由于进行解析,前导零将被删除;如果解析失败,则只需打印子字符串即可。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Main {
    public static void main(String[] args) {
        String str = "aoeu01234stnh0987";
        Matcher matcher = Pattern.compile("\\p{L}+|[0-9]+").matcher(str);
        while (matcher.find()) {
            String substring = matcher.group();
            try {
                System.out.println(Integer.parseInt(substring));
            } catch (NumberFormatException e) {
                System.out.println(substring);
            }
        }
    }
}

输出:

aoeu
1234
stnh
987