gpt4 book ai didi

Java : String to table

转载 作者:行者123 更新时间:2023-12-01 15:52:41 24 4
gpt4 key购买 nike

在Java中,我有一个像这样的字符串“0564\n5523\n5445\n8596”,我或多或少希望制作一个这样的表格:

. * . .
* * . .
* . . *
. * . .

其中 * 表示等于 5 和 .表示它不等于 5。

基本字符串是直接从文本文件中提取的(仍然不知道我将如何做到这一点,但是如果有人有关于它的简单明了的文档......;-))。

我想要做的方法是这样的(我知道表格的初始尺寸并且字符串将始终与尺寸匹配)

int counter = 0;
for (int r=0;r<size;r++)
{
for (int c=0;c<size;c++)
{
if thestring.charAt(counter)=='5'
{
thetable[c][r]='*';
}
else
{
thetable[c][r]='.';
}
counter++;
}
counter = counter+2; //To skip the \n.
}

所以基本上我的第一个问题是“还有其他方法吗?”我非常不喜欢那个,因为“跳过”我不想评估的角色似乎很蹩脚。

第二个问题(我只是想确定)是“\n 是否被视为字符串中的 2 个字符?”

最后一个问题更多的是关于文本文件,如果我从中提取字符串的文本文件是在Windows上,那么该字符串不会像“0564\r\n5523\r\n5445\r\n8596”吗?

最佳答案

作业?

public class d {
public static void main(String[] args) {
String s = "0564\n5523\n5445\n8596";
System.out.println(s.replaceAll("[^5\n]", ".")
.replace('5', '*')
.replaceAll("(.)(?!\n|$)", "$1 ")
.replaceAll("(\r|\n|\r\n)", System.getProperty("line.separator")));
}
}

关于Java : String to table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5694259/

24 4 0