简体   繁体   English

将多行字符串存储为二维字符数组

[英]Storing multi line string as 2d array of chars

I am trying to store a multiline string as an array of chars.我正在尝试将多行字符串存储为字符数组。 Essentially the string input is a game board where the '#' are the walls and ' ' are open spaces.本质上,字符串输入是一个游戏板,其中“#”是墙壁,“”是开放空间。 The first line simply specifies that the board is 8x8 chars.第一行简单地指定板是 8x8 字符。

String input as code:字符串输入作为代码:

            "8\r\n"
            + "########\r\n"
            + "P #    #\r\n"
            + "# # ## #\r\n"
            + "# #  #G#\r\n"
            + "#    ###\r\n"
            + "#### # #\r\n"
            + "#G   #G#\r\n"
            + "########";

What i am trying to do is store this multi line string so that i get a 2d array that would store it like this:我想做的是存储这个多行字符串,以便我得到一个像这样存储它的二维数组:

'#''#''#''#''#''#''#''#'
'P'' ''#'' '' '' '' ''#'
'#'' ''#'' ''#''#'' ''#'
etc..

Try this.尝试这个。

String input = "8\r\n"
    + "########\r\n"
    + "P #    #\r\n"
    + "# # ## #\r\n"
    + "# #  #G#\r\n"
    + "#    ###\r\n"
    + "#### # #\r\n"
    + "#G   #G#\r\n"
    + "########";
char[][] result = input.lines()
    .skip(1)
    .map(String::toCharArray)
    .toArray(char[][]::new);
for (char[] line : result)
    System.out.println(Arrays.toString(line));

output: output:

[#, #, #, #, #, #, #, #]
[P,  , #,  ,  ,  ,  , #]
[#,  , #,  , #, #,  , #]
[#,  , #,  ,  , #, G, #]
[#,  ,  ,  ,  , #, #, #]
[#, #, #, #,  , #,  , #]
[#, G,  ,  ,  , #, G, #]
[#, #, #, #, #, #, #, #]

Try this using Stream API:使用 Stream API 试试这个:

     String str = "8\r\n"
            + "########\r\n"
            + "P #    #\r\n"
            + "# # ## #\r\n"
            + "# #  #G#\r\n"
            + "#    ###\r\n"
            + "#### # #\r\n"
            + "#G   #G#\r\n"
            + "########";

     char[][] result = Arrays.stream(str.split("\r\n"))
                             .skip(1)
                             .map(String::toCharArray)
                             .toArray(char[][]::new);

And then there is the non-streams approach.然后是非流方法。

  • Split the line on the line terminator在行终止符上拆分行
  • Allocate an array of char ( charArray ) to hold all but the first line分配一个 char ( charArray ) 数组来保存除第一行之外的所有内容
  • For each of the lines, convert the line to a character array and assign to the charArray , ensuring to start with the second line.对于每一行,将该行转换为字符数组并分配给charArray ,确保从第二行开始。
String[] lines = input.split("\r\n");
char[][] charArray = new char[lines.length-1][];    
for (int i = 0; i < charArray.length; i++) {
    charArray[i] = lines[i+1].toCharArray();
}
for(char[] c : charArray) {
    System.out.println(Arrays.toString(c));
}

Prints印刷

[#, #, #, #, #, #, #, #]
[P,  , #,  ,  ,  ,  , #]
[#,  , #,  , #, #,  , #]
[#,  , #,  ,  , #, G, #]
[#,  ,  ,  ,  , #, #, #]
[#, #, #, #,  , #,  , #]
[#, G,  ,  ,  , #, G, #]
[#, #, #, #, #, #, #, #]

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

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