简体   繁体   中英

Multi-line string to array

I have a multi-line string:

40 40 40 
100 100 100
200 200 200
100 50 200 100
150 150 150
50 60 70 80 90

and I need it as 2D array. I was trying to do it by split, guava Splitter and couple of more techniques but it still doesn't want to work.

public void readTextFile() throws IOException {
        content = new String(Files.readAllBytes(Paths.get("/home/cosaquee/dane.txt")));

        Splitter niceCommaSplitter = Splitter.on('\n').omitEmptyStrings().trimResults();

        Iterable<String> tokens2 = niceCommaSplitter.split(content);

        for(String token: tokens2){
            boolean atleastOneAlpha = token.matches(".*[a-zA-Z]+.*");
            if (!atleastOneAlpha) {
                arrayList.add(token);
                System.out.println(token);
            }
        }
    }

That is my code for now. I have arraylist with every line but I don't know how to make it to 2D array. I tried good old for s but don't know how to iterate over every string and split them and save to array.

Why use a Splitter? String comes with a split() method. Also, just use a double for loop to fill up your 2d array.

public String[][] readTextFile() throws IOException {
    String content = new String(Files.readAllBytes(Paths.get("yourpath.txt")));

    // get the lines
    String[] lines = content.split("\\r?\\n"); // split on new lines

    // get the max amt of nums in the file in a single line
    int maxInLine = 0;
    for (String x : lines) {
        String[] temp = x.split("\\s+"); // split on whitespace
        if (temp.length > maxInLine) {
            maxInLine = temp.length;
        }
    }

    String[][] finalArray = new String[lines.length][maxInLine]; // declare and instantiate the array of arrays

    // standard double for loop to fill up your 2D array
    for (int i = 0; i < lines.length; i++) {
        String[] temp = lines[i].split("\\s+"); // split on whitespace
        for (int j = 0; j < temp.length; j++) {
            finalArray[i][j] = temp[j];
        }
    }
    return finalArray;
}

Using Guava, you can produce a list of lists in a one-liner -- applying a Function for each row that takes as input a String containing whitespace-separated columns and outputting the columns of the row as List<String> . If you prefer a 2d array of strings, then you need some more code:

public void readTextFile() throws IOException {
    String content = new String(Files.readAllBytes(Paths
            .get("/home/cosaquee/dane.txt")));

    // convert the string into a list of lists, corresponding to a 2d string array
    List<List<String>> twoDimensionalList = Lists
            .transform(Splitter.on(System.lineSeparator()).splitToList(content),
                    new Function<String, List<String>>() {
                        @Override
                        public List<String> apply(String row) {
                            return Splitter.on(" ").splitToList(row);
                        }
                    });

    // convert the list of lists into a 2d array
    String[][] twoDimensionalArray = new String[twoDimensionalList.size()][];

    for (int i = 0; i < twoDimensionalArray.length; i++) {
        twoDimensionalArray[i] = twoDimensionalList.get(i).toArray(
                new String[twoDimensionalList.get(i).size()]);
    }

    // assert that we got it right
    for (String[] row : twoDimensionalArray) {
        for (String col : row) {
            System.out.print(col + " ");
        }
        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