java - 多行字符串到数组

标签 java arrays guava

我有一个多行字符串:

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

我需要它作为二维数组。我试图通过 split、 Guava Splitter 和其他一些技术来做到这一点,但它仍然不起作用。

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

这就是我现在的代码。我的每一行都有数组列表,但我不知道如何将其变成二维数组。我尝试了旧的 for ,但不知道如何迭代每个字符串并将它们拆分并保存到数组。

最佳答案

为什么要使用分离器?字符串带有 split() 方法。另外,只需使用双 for 循环来填充二维数组。

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

关于java - 多行字符串到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30581614/

相关文章:

java - 从 Guava EventBus 订阅者抛出异常

java - 将 MutableClassToInstanceMap 与泛型一起使用时出现编译错误

java - 玩!框架运行抛出 UnsupportedClassVersionError

java - 如何在 linux (RedHat 6) 上检查 java 版本

ios - Swift3 iOS - 如何在 URL 数组 [URL?] 中搜索 URL

javascript - JS 关联数组 : add new pair

Java8 : Why a lambda expression could do a logical and(or) with boolean

java - 为什么java中没有使用指针概念?

c - 使用指向现有数组的指针初始化数组

java - Google Guava Cache,刷新过期超时