So to explicitly state the task: You want to convert a sequence of two or more digits into the sum of those digits. The sum is guaranteed to be 8 or less, i.e. to also be a single digit.
There are many ways to do that, but the closest to what you're trying would likely be:
static String normalizeFen(String fen) {
StringBuilder buf = new StringBuilder(fen);
for (int i = 1; i < buf.length(); i++) {
if (Character.isDigit(buf.charAt(i)) && Character.isDigit(buf.charAt(i - 1))) {
// Found 2 consecutive digits, so sum them
int sum = Character.digit(buf.charAt(i - 1), 10)
+ Character.digit(buf.charAt(i), 10);
buf.setCharAt(i - 1, Character.forDigit(sum, 10));
buf.deleteCharAt(i); // Remove second digit
i--; // Go back to reprocess the same index position again
}
}
return buf.toString();
}
Tests
System.out.println(normalizeFen("1P111Pr1"));
System.out.println(normalizeFen("rnbqkbnr/pp1ppppp/11111111/11p11111/1111P111/11111111/PPPP1PPP/RNBQKBNR"));
Output
1P3Pr1
rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR