I have a String
for an editor in a 2D platform game, where the user clicks on a 16x60 rectangle board to create a custom board. I loop through these rectangles and get a String that I'd like to trim down. The x's are blocks, and a's are empty space. I need this to draw the level.
String s = "x1x1x1x1a1a1x1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1";
I want to trim this to x4a2x1a54
. Basically adding up the x's and a's that show up right after each other.
How do I do this?
Loop though the characters and store the last alphabetic character. For each of those chars parse the number that follows it. It the alphabetic char is the same as the last one you can add this number to the count, otherwise write the old results to the output:
public static String compress(String input) {
if (input == null || input.isEmpty()) {
return input;
}
char type = ' ';
int count = 0;
StringBuilder output = new StringBuilder();
int index = 0;
final int length = input.length();
while (index < length) {
char elementType = input.charAt(index);
// parse number
int elementCount = 0;
char c;
for (index++; index < length && Character.isDigit(c = input.charAt(index)); index++) {
elementCount = 10 * elementCount + (c - '0');
}
if (elementType == type) {
count += elementCount;
} else {
// finish counting last type
output.append(type).append(count);
type = elementType;
count = elementCount;
}
}
output.delete(0, 2); // remove substring added for the initial count/type
output.append(type).append(count); // append last entry
return output.toString();
}
This allows you to output numbers different to 1
, e.g.
compress("a22a20x9")