Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

149
Vistas
Replacing the number with the number of spaces

I have a String:

String example = "AA5DD2EE3MM";

I want to replace the number with the number of spaces. Example:

String example = "AA     DD  EE   MM"

If the String would be

String anotherExample = "a3ee"

It should turn into:

String anotherExample = "a   ee"

I want to do it for any string. Not only for the examples above.

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Split your input at digit and non digit chars as a stream, map digits to the corsponding number of spaces using String.repeat, collect to string using Collectors.joining():

String input  = "AA5DD2EE3MM";
String regex  = "(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)";
String result = Pattern.compile(regex)
                        .splitAsStream(input)
                        .map(s -> s.matches("\\d+") ? " ".repeat(Integer.parseInt(s)) : s)
                        .collect(Collectors.joining());
over 4 years ago · Santiago Trujillo Denunciar

0

You could also use this approach, which is simpler but also far less elegant:

String example = "a4aa";
String newString = "";

for (int i = 0; i < example.length(); i++) {
    if (Character.isDigit(example.charAt(i))) {
        for (int a = 0; a < Character.getNumericValue(example.charAt(i)); a++) {
            newString += " ";
        }
    } else {
        newString += example.charAt(i);
    }
}
System.out.println(newString);
over 4 years ago · Santiago Trujillo Denunciar

0

Using a pattern matcher approach:

String input = "AA5DD2EE3MM";
Pattern pattern = Pattern.compile("\\d+");
Matcher m = pattern.matcher(input);
StringBuffer buffer = new StringBuffer();

while (m.find()) {
    m.appendReplacement(buffer,new String(new char[Integer.valueOf(m.group())]).replace("\0", " "));
}
m.appendTail(buffer);
System.out.println(buffer.toString());  // AA     DD  EE   MM

The idea here is to iterate the string, pausing at each digit match. We replace each digit with space replicated the same number of times as the digit.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda