gpt4 book ai didi

java - ReplaceAll 不适用于 String[] 元素

转载 作者:行者123 更新时间:2023-12-01 07:46:53 25 4
gpt4 key购买 nike

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

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

输出为

rnbqkbnrrnbqkbnrpppppppppppppppp88888888PPPPPPPPPPPPPPPPRNBQKBNRRNBQKBNR

但应该是

rnbqkbnrrnbqkbnrpppppppppppppppp811111111811111111811111111811111111PPPPPPPPPPPPPPPPRNBQKBNRRNBQKBNR

最佳答案

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

 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用于正则表达式。

关于java - ReplaceAll 不适用于 String[] 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49995736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com