簡體   English   中英

多行字符串到數組

[英]Multi-line string to array

我有一個多行字符串:

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

我需要它作為2D數組。 我試圖通過拆分,番石榴拆分器和其他幾種技術來實現它,但它仍然不起作用。

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

那是我現在的代碼。 我每一行都有arraylist,但是我不知道如何將其變成2D數組。 for s嘗試了old old for但不知道如何遍歷每個字符串並將其拆分並保存到數組。

為什么要使用分離器? 字符串帶有split()方法。 此外,只需使用double for循環即可填充2d數組。

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

使用Guava,您可以單行生成列表列表-對每行應用一個Function ,該Function將包含空格分隔的列的String作為輸入並將行的列輸出為List<String> 如果您更喜歡二維字符串數組,則需要更多代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM