0

所以我有这个字符串StringBuilder fenToString = new StringBuilder("1P111Pr1")

现在我怎么能把它改成a = "1P3Pr1"

我试过这个

int fenNum = 0;
for(int i = 0; i < fenToString.length(); i++){
        if(Character.isDigit(fenToString.charAt(i))){
            fenNum += 1;
            fenToString.setCharAt(i, (char)(fenNum+'0'));
        }else{
            fenNum = 0;
        }
    }

我得到"1P123Pr1"而不是"1P3Pr1"

4

2 回答 2

1

因此,明确说明任务:您希望将两个或多个数字的序列转换为这些数字的总和。总和保证为 8 或更少,即也是一位数。

有很多方法可以做到这一点,但最接近您尝试的方法可能是:

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

测试

System.out.println(normalizeFen("1P111Pr1"));
System.out.println(normalizeFen("rnbqkbnr/pp1ppppp/11111111/11p11111/1111P111/11111111/PPPP1PPP/RNBQKBNR"));

输出

1P3Pr1
rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR
于 2021-02-11T14:36:20.477 回答
0

可以在不删除以下字符的情况下转换 FEN 字符串StringBuilder

static String fixFenString(String fen) {
    // debug print
    System.out.print(fen + " -> ");

    StringBuilder fenToString = new StringBuilder(fen.length());
    int fenNum = 0;
    for (int i = 0; i < fen.length(); i++) {
        if(Character.isDigit(fen.charAt(i))) {
            fenNum += fen.charAt(i) - '0';
        } else {
            if (fenNum > 0) {
                fenToString.append(fenNum);
                fenNum = 0;
            }
            fenToString.append(fen.charAt(i));
        }
    }
    // add last digit if available
    if (fenNum > 0) {
        fenToString.append(fenNum);
    }
    return fenToString.toString();
}

测试:

System.out.println(getFenString("1P111P11"));
System.out.println(getFenString("1P12PP1"));
System.out.println(getFenString("1P131P"));
System.out.println(getFenString("rnbqkbnr/pp1ppppp/11111111/11p11111/1111P111/11111111/PPPP1PPP/RNBQKBNR"));

输出:

1P111P11 -> 1P3P2
1P12PP1 -> 1P3PP1
1P131P -> 1P5P
rnbqkbnr/pp1ppppp/11111111/11p11111/1111P111/11111111/PPPP1PPP/RNBQKBNR ->
rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR
于 2021-02-11T16:10:11.637 回答