使用String.split()循环遍历2d数组

时间:2018-05-23 12:12:44

标签: java arrays loops

我遇到了一个简单的问题,但我是来自PHP的Java新手。我需要将分隔的文本文件拆分为数组。我把它分解成一系列线条,每一条都看起来像这样:

{
    {Bob | Smithers | Likes Cats | Doesnt Like Dogs},
    {Jane | Haversham | Likes Bats | Doesnt Like People}
}

我需要把它变成一个二维数组。

在PHP中,它很简单。你只需使用explode();我尝试在1d数组上使用String.split,它也不是那么糟糕。事情是,我还没有学会如何对Java好。所以我不知道如何遍历数组并将其转换为2d。这就是我所拥有的:

for (i = 0; i < array.length; i++) {
    String[i][] 2dArray = array[i].split("|", 4);
}

PHP将是

for ($i = 0; $i < count($array); $i++) {
    $array[i][] = explode(",", $array[i]);
}

2 个答案:

答案 0 :(得分:0)

你可以像这样循环数组:

    // Initialize array
    String[] array = {
            "Bob | Smithers | Likes Cats | Doesnt Like Dogs",
            "Jane | Haversham | Likes Bats | Doesnt Like People"
    };

    // Convert 1d to 2d array
    String[][] array2d = new String[2][4];
    for(int i=0;i<array.length;i++) {
        String[] temp = array[i].split(" \\| ");

        for(int j=0;j<temp.length;j++) {
            array2d[i][j] = temp[j];
        }
    }

    // Print the array
    for(int i=0;i<array2d.length;i++) {
        System.out.println(Arrays.toString(array2d[i]));
    }

注意:我使用\\|拆分管道符。

答案 1 :(得分:0)

问题

如果我说得对,你有这样的输入:

{{Bob | Smithers | Likes Cats | Doesnt Like Dogs},{Jane | Haversham | Likes Bats | Doesnt Like People}}

可读版本:

{
    {Bob | Smithers | Likes Cats | Doesnt Like Dogs},
    {Jane | Haversham | Likes Bats | Doesnt Like People}
}

并且您希望在二维String aray,String[][]中表示该结构。

解决方案

关键是方法String#split,它将给定的String拆分为由给定符号分隔的子字符串。您的示例中为,|

首先,我们删除所有{},因为我们不需要它们(只要文本本身不包含分隔符):

String input = ...
String inputWithoutCurly = input.replaceAll("[{}]", "");

现在的文字是:

Bob | Smithers | Likes Cats | Doesnt Like Dogs,Jane | Haversham | Likes Bats | Doesnt Like People

接下来,我们要创建数组的外部维度,由,分割:

String[] entries = inputWithoutCurly.split(",");

结构现在是:

[
    "Bob | Smithers | Likes Cats | Doesnt Like Dogs",
    "Jane | Haversham | Likes Bats | Doesnt Like People"
]

我们现在想要将每个内部文本拆分成它们的组件。因此,我们迭代所有条目,将它们分开|并将它们收集到结果中:

// Declaring a new 2-dim array with unknown inner dimension
String[][] result = new String[entries.length][];

// Iterating all entries
for (int i = 0; i < entries.length; i++) {
    String[] data = entries[i].split(" | ");

    // Collect data to result
    result[i] = data;
}

最后我们有了所需的结构:

[
    [ "Bob", "Smithers", "Likes Cats", "Doesnt Like Dogs" ],
    [ "Jane", "Haversham", "Likes Bats", "Doesnt Like People"]
]

一切紧凑:

String[] entries = input.replaceAll("[{}]", "").split(",");
String[][] result = new String[entries.length][];

for (int i = 0; i < entries.length; i++) {
    result[i] = entries[i].split(" | ");
}

如果你有Java 8或更新版本,你可以使用 Stream API 来实现紧凑的功能:

String[][] result = Arrays.stream(input.replaceAll("[{}]", "").split(","))
    .map(entry -> entry.split(" | "))
    .toArray(String[][]::new);