Replacing the number with the number of spaces

Viewed 236

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.

5 Answers

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());

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);

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.

public static String replaceDigitsWithSpaces(String input) {
    String result = "";
    int len = input.length(), i =0;
    
    while( i < len) {
        
        if(Character.isLetter(input.charAt(i))) {
            result += input.charAt(i);
        }else if(Character.isDigit(input.charAt(i))) {
            //generate number upto characters
            int k = 0, j = i;
            String temp = "";
            while(j < len) {
                if(Character.isDigit(input.charAt(j))) {
                    temp += input.charAt(j);
                    j++;
                }else {
                    break;
                }
            }
            k = Integer.parseInt(temp);
            while(k != 0) {
                result+= " ";
                k--;
            }
            i = j;
            continue;
        }
        i++;
    }
    return result;
}

input:: "AA23BB1C11C8"<br>
output:: AA                       BB C           C        .

StringBuilder is more efficient for concatenation:

    public static String spaceIt(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                for (int j = 0; j < Character.digit(c, 10); j++) {
                    sb.append(' ');
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
Related