Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda