首页 > 解决方案 > 解析/转换包含字符和数字的任务

问题描述

有必要重复该字符,其次数与其后面的数字一样多。

它们是正整数。

case #1

input: "abc3leson11"

output: "abccclesonnnnnnnnnnn"

我已经通过以下方式完成了它:

    String a = "abbc2kd3ijkl40ggg2H5uu";
    String s = a + "*";
    String numS = "";
    int cnt = 0;
    for (int i = 0; i < s.length(); i++) {
        char ch = s.charAt(i);
        if (Character.isDigit(ch)) {
            numS = numS + ch;
            cnt++;
        } else {
            cnt++;
            try {
                for (int j = 0; j < Integer.parseInt(numS); j++) {
                    System.out.print(s.charAt(i - cnt));
                }
                if (i != s.length() - 1 && !Character.isDigit(s.charAt(i + 1))) {
                    System.out.print(s.charAt(i)); 
                }
            } catch (Exception e) {
                if (i != s.length() - 1 && !Character.isDigit(s.charAt(i + 1))) {
                    System.out.print(s.charAt(i)); 
                }
            }
            cnt = 0;
            numS = "";
        }

    }

但我想知道有没有更好的解决方案,代码更少更干净?

标签: javafor-loopif-statementnumbers

解决方案


你能看看下面吗?我正在使用StringUtils来自Apache Common Utils的库来重复字符:

public class MicsTest {

    public static void main(String[] args) {
        String input = "abc3leson11";
        String output = input;
        Pattern p = Pattern.compile("\\d+");
        Matcher m = p.matcher(input);
        while (m.find()) {
          int number = Integer.valueOf(m.group());
          char repeatedChar = input.charAt(m.start()-1);
          output = output.replaceFirst(m.group(), StringUtils.repeat(repeatedChar, number));
        }
        System.out.println(output);
    }
}

如果您不想使用StringUtils. 您可以使用以下自定义方法来达到相同的效果:

    public static String repeat(char c, int times) {
        char[] chars = new char[times];
        Arrays.fill(chars,  c);
        return new String(chars);
    }

推荐阅读