ReplaceAll不在String []元素上工作

时间:2018-04-24 07:27:29

标签: java replaceall

我需要编写国际象棋程序,使用FEN作为创建国际象棋棋盘的参数。为了简化这个过程,我想用等量的" 1"来替换数字。使用replaceAll方法查找该数字(查看我的代码)。不幸的是,这不起作用,我不知道为什么。有人可以告诉我我应该采取哪些不同的做法?

String[] read2 = new String[] {"rnbqkbnr", "pppppppp", "8", "8", "8", "8", "PPPPPPPP", "RNBQKBNR"};         
for (int i = 0; i < 8; i++ ) {
    System.out.println(read2[i]);
    read2[i].replaceAll("8", "11111111");
    read2[i].replaceAll("7", "1111111");
    read2[i].replaceAll("6", "111111");
    read2[i].replaceAll("5", "11111");
    read2[i].replaceAll("4", "1111");
    read2[i].replaceAll("3", "111");
    read2[i].replaceAll("2", "11");
    System.out.println(read2[i]);   
}

输出

rnbqkbnr
rnbqkbnr
pppppppp
pppppppp
8
8
8
8
8
8
8
8
PPPPPPPP
PPPPPPPP
RNBQKBNR
RNBQKBNR

但应该是

rnbqkbnr
rnbqkbnr
pppppppp
pppppppp
8
11111111
8
11111111
8
11111111
8
11111111
PPPPPPPP
PPPPPPPP
RNBQKBNR
RNBQKBNR

1 个答案:

答案 0 :(得分:6)

您需要在数组中保存结果以使用新值替换旧值,您通过调用现有字符串上的替换来生成新字符串,而不是将新字符串分配给对象引用。

 String[] read2 = new String[] {"rnbqkbnr", "pppppppp", "8", "8", "8", "8", "PPPPPPPP", "RNBQKBNR"};

for (int i = 0; i < 8; i++ ) {

    System.out.println(read2[i]);
    read2[i] = read2[i].replace("8", "11111111");
    read2[i] = read2[i].replace("7", "1111111");
    read2[i] = read2[i].replace("6", "111111");
    read2[i] = read2[i].replace("5", "11111");
    read2[i] = read2[i].replace("4", "1111");
    read2[i] = read2[i].replace("3", "111");
    read2[i] = read2[i].replace("2", "11");
    System.out.println(read2[i]);

}

编辑:正如评论中所建议的那样使用replace而不是replaceAll,因为replaceAll用于正则表达式。