Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!