简体   繁体   中英

How to delete spaces In an 2D-Array in Java?

I have a text file. I am reading it then placing it into a 2D-Array. There are spaces. I need to get rid of those spaces. But I can't use trim properly. Here is my code:

while ((line = br.readLine() ) != null ){

    char[] row = line.toCharArray();
    line.trim();
    int counter = 0;
    for (int i = 0; i < row.length; i++) {
        maze[counter][i] = row[i];
        System.out.print(maze[i]);
        counter++;
    }
    System.out.printf("%n");
}

The output is as follows:

1                    1                    1                    0
0                    0                    1                    0
0                    0                    1                    0
0                    9                    1                    0

The elements in the text file I read has one space between each other. But I get too many spaces as output. I need to get this as

1110
0010
0010
0910

I think I should use trim method, but I could not figure it out.

You can use String#split with a regular expression of something like \\s+ , for example...

    String text = "1                    1                    1                    0";
    String elements[] = text.split("\\s+");
    for (String value : elements) {
        System.out.println("[" + value + "]");
    }

Which outputs

[1]
[1]
[1]
[0]

(The braces are there to demonstrate that no spaces remain)

In your example I might still be tempted to still us line = line.trim(); to ensure that there are no leading or trailing space which might cause empty values to be included...

You can use (string).replace(" ", '\\0') to replace all spaces with blanks

For example:

    String line = "1 2  2 3 4 2 122 23  3  3 3 3";   //example
    line = line.replace(' ', '\0');  //'\0' is the key for blank (or nothing)
    System.out.println(line);

will produce

122342122233333

This will get rid of the spaces and only use the valid input (ie the numbers). It says row, but the only input will be the same characters.

Hope this helps.

Quickest way for me would be to just use a nested loop to print each element of the array individually. Eg

String [][] maze = new String [4][4];

     for (int i = 0; i < maze.length; i++) {

         maze[i][0] = "1";
         maze[i][1] = "0";
         maze[i][2] = "1";
         maze[i][3] = "0";

     }

     for (int k =0;k<maze.length;++k){

         for(int j=0;j<maze.length;++j)
         {
             System.out.print(maze[k][j]);
         }
         System.out.println();
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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