拆分“\ n”Java

时间:2015-03-03 14:45:43

标签: java eclipse string list newline

所以我把我的String写成了一个文件 (将“\ n”写为“\ n”以使它们显示为“\ n”) 但是当我从文件中获取字符串时,它不会分裂为“\ n”。我知道字符串是我想要的,但是你可以在这个截图中看到: http://imgur.com/VUcMPeV

拆分变成一个只包含一个元素的列表(这是整个String,以及当我尝试获取列[1]时它崩溃的原因),并且它不会分裂为“\ n”。

你们任何人都可以帮我找出原因吗?

以下是屏幕显示中显示的代码(但没有控制台输出)

public void loadGame(String boardInput){
    String column[] = boardInput.split("\n");
    System.out.println(column[0]);
    boardWidth = column[1].length();
    for (int y = 0; y < column.length; y++){
        if ( column[y].contains("@") || column[y].contains("+")){
            currentY = y;
        }
        ArrayList<Cell> row = new ArrayList<Cell>();
        String Chars[] = column[y].split("");
        for (int x = 0; x < column[y].length(); x++){
            if ( Chars[x].equals("@") || Chars[x].equals("+")){
                currentX = x;
            }
            if (Chars[x].equals(".") || Chars[x].equals("+") || Chars[x].equals("*")){
                row.add(new Cell(Chars[x], true));
            } else {
                row.add(new Cell(Chars[x], false));
            }
            }
            board.add(row);
    }
}

这是boardInput的值:*######*\n# @ #\n# $ . #\n# #\n*######*

3 个答案:

答案 0 :(得分:2)

使用:

String column[] = boardInput.split("\\n");

"\n"是“换行符”的特殊字符。额外的\会逃避另一个\,因此它会被视为文本\n,而不再是特殊字符。

了解Escape Sequences here

答案 1 :(得分:1)

使用s.split("\\n")在特殊字符之前使用\http://www.javapractices.com/topic/TopicAction.do?Id=96

答案 2 :(得分:0)

我和你有同样的问题,其他答案对我也不起作用。
因此,我尝试了以下操作:.split("\\\\n"),它确实起作用。我认为我们的输入有些有趣,因此有必要进行双重转义。