且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将字符串转换为多维数组

更新时间:2023-02-14 13:04:44

如果你想使用 Stream 试试这个:

If you want to use Stream try this:

    Pattern PAIR = Pattern.compile("(?<=\\d)\\s(?=\\d)");

    double[][] result = PAIR.splitAsStream(stringProfile)
            .map(pair -> pair.split(","))
            .map(pair -> new double[] { FastMath.toRadians(Double.valueOf(pair[0])), FastMath.toRadians(Double.valueOf(pair[1])) })
            .toArray(i -> new double[i][]);

A 模式用于拆分 stringProfile 在空白字符上有后面的数字提前它们。这会产生一个 Stream 的字符串,其中包含一对数字除以','。我们拆分第一个地图中的','上的这个字符串获取表示数字的字符串数组。在下一个 map 中,解析的数字和它们的弧度被计算出来。

A Pattern is used to split stringProfile on whitespace characters which have a digit behind and ahead them. This results in a Stream of strings which contains a pair of numbers divided by ', '. We split this string on ',' in a first map to get an array of strings representing the numbers. In the next map the numbers a parsed and their radians is computed.

我们可以解析数字以及弧度到单个 map 步骤的共同点。以下代码更详细,但创建了一个额外的双数组:

We could devide the parsing of the numbers and the comuputation of the radians to single map steps. The following code is more verbose but creates an additional double array:

double[][] result = PAIR.splitAsStream(stringProfile)
        .map(pair -> pair.split(","))
        .map(pair -> new double[] { Double.valueOf(pair[0]), Double.valueOf(pair[1]) })
        .map(pair -> new double[] { FastMath.toRadians(pair[0]), FastMath.toRadians(pair[1]) })
        .toArray(i -> new double[i][]);

如果我们想重用双数组,我们可以这样做:

If we want to reuse the double array, we can do this like this:

        .map(pair -> {
            pair[0] = FastMath.toRadians(pair[0]);
            pair[1] = FastMath.toRadians(pair[1]);
            return pair;
        })

最后一步将双数组收集到一个二维数组中。

The last step collects the double arrays into a two dimensional array.

编辑:

查看此演示

使用模式类使用的模式查找空白字符( \\\\ )之前((?< = \\d) = 看后面)并成功((?= \\d) = 展望未来)电子数字( \\\\ )。这些外观具有零宽度,因此它们被评估为捕获(匹配)但不是匹配序列的一部分( Matcher.group( ) )。 匹配序列仅包含空格字符( \\\\ )。

Using the wording of the documentation of the Pattern class the used pattern looks for a whitespace character (\\s) which is preceded ((?<=\\d) = look behind) and succeeded ((?=\\d) = look ahead) by one digit (\\d). These looks have zero-width, thus they are evaluated for capturing (matching) but are not part of the matched sequence (Matcher.group()). The matching sequence contains only a whitespace character (\\s).

对于 stringProfile 这种模式在两种情况下匹配:8 13 2。在这些情况下,两个数字围绕。另一方面,例如0,4不匹配。 的出现会阻止匹配。

For stringProfile this pattern will match in two cases: "8 1" and "3 2". In these cases two digits are surrounding a " ". On the other hand e.g. "0, 4" doesn't match. The occurrence of "," prevents a match.