简体   繁体   English

在“\\n”Java 上拆分

[英]Splitting on “\n” Java

So I have written my String to a file ( wrote the "\\n"s as "\\n" to make them appear as "\\n") But when I get the String back from the file it wont split on the "\\n"'s.所以我已经将我的字符串写入一个文件(将“\\n”写为“\\n”以使它们显示为“\\n”)但是当我从文件中取回字符串时,它不会在“\\n ”的。 I know that the string is what I want it to be, but as you can see in this screenshot: http://imgur.com/VUcMPeV我知道该字符串是我想要的,但正如您在此屏幕截图中所看到的: http : //imgur.com/VUcMPeV

the split turns into a list with only one element (which is the whole String, and also why it crashes when I try to get column[1]), and it doesnt split on the "\\n"'s.拆分变成一个只有一个元素的列表(这是整个字符串,也是为什么当我尝试获取列 [1] 时它崩溃),并且它不会在“\\n”上拆分。

Can any of you help me figure out why?你们中的任何人都可以帮我弄清楚原因吗?

Here is the code as displayed in the screenshow (but without the console output)这是屏幕显示中显示的代码(但没有控制台输出)

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

And this is the value of boardInput: *######*\\n# @ #\\n# $ . #\\n# #\\n*######*这是 boardInput 的值: *######*\\n# @ #\\n# $ . #\\n# #\\n*######* *######*\\n# @ #\\n# $ . #\\n# #\\n*######*

Use:用:

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

"\\n" is the special character for the "line break". "\\n"是“换行符”的特殊字符。 The additional \\ escapes the other \\ so it is read as the text \\n and not the special character any longer.额外的\\转义了另一个\\因此它被读作文本\\n而不是特殊字符。

Read about Escape Sequences here . 在此处阅读有关转义序列的信息

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

I had the same issue as you, and the other answers didn't work for me either.我和你有同样的问题,其他答案对我也不起作用。
So I tried this: .split("\\\\\\\\n") and that worked.所以我尝试了这个: .split("\\\\\\\\n")并且有效。 I assume there is something funny with our input that makes the double escaping necessary.我认为我们的输入有一些有趣的地方使得双重转义是必要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM