Java:字符串到表

时间:2011-04-17 15:06:22

标签: java string character text-files

在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.
}

所以基本上我的第一个问题是“还有其他办法吗?”我完全不喜欢那个,因为“跳过”我不想评价的人物似乎很蹩脚。

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

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

2 个答案:

答案 0 :(得分:1)

作业?

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

答案 1 :(得分:0)

第一个问题:为什么不做一个replaceAll?即

str.replaceAll("5", "*").replaceAll("[0-9]", ".")

第二个问题:&#34; \ n&#34;被视为一个角色。

第3个问题:如果它是在Windows中创建的。