análisis / las tareas de conversión con caracteres y números dentro de

maria:

Es necesario repetir el carácter, tantas veces como el número detrás de él.

Ellos son números enteros positivos.

case #1

input: "abc3leson11"

output: "abccclesonnnnnnnnnnn"

Ya termino de la siguiente manera:

    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 = "";
        }

    }

Pero me pregunto ¿hay alguna solución mejor con menos y un código más limpio?

caballeros:

Utilización de Java cadena básica regxdebería hacerla más concisa de la siguiente manera:

public class He1 {
    private static final Pattern pattern = Pattern.compile("[a-zA-Z]+(\\d+).*");  
    // match the number between or the last using regx;
    public static void main(String... args) {
        String s = "abc3leson11";
        System.out.println(parse(s));
        s = "abbc2kd3ijkl40ggg2H5uu";
        System.out.println(parse(s));
    }

    private static String parse(String s) {
        Matcher matcher = pattern.matcher(s);
        while (matcher.find()) {
            int num = Integer.valueOf(matcher.group(1));
            char prev = s.charAt(s.indexOf(String.valueOf(num)) - 1); 
            // locate the char before the number;
            String repeated = new String(new char[num-1]).replace('\0', prev); 
            // since the prev is not deleted, we have to decrement the repeating number by 1;
            s = s.replaceFirst(String.valueOf(num), repeated);
            matcher = pattern.matcher(s);
        }
        return s;
    }
}

Y la salida debe ser:

abccclesonnnnnnnnnnn
abbcckdddijkllllllllllllllllllllllllllllllllllllllllggggHHHHHuu

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=137686&siteId=1
Recomendado
Clasificación