【问题标题】:Build a jagged array from a String in Java [closed]从 Java 中的字符串构建锯齿状数组 [关闭]
【发布时间】:2020-10-24 11:36:24
【问题描述】:

我必须编写这个“从String 创建一个矩阵:

 * The string if formatted as follow:
 *  - Each row of the matrix is separated by a newline
 *    character \n
 *  - Each element of the rows are separated by a space
 *  For example, the String "0 1\n2 3" represent the
 *  matrix:
      [0 1]
      [2 3]
  

在练习中,矩阵可以是“锯齿状数组”,这是我的代码:

int[][] tab = null 
int compteur = 0
int position = 0
for (int i = 0; i < s.length(); i++) {
    char l = s.charAt(i);
    String p = String.valueOf(l);
    if (Character.isDigit(s.charAt(i))) {
        tab[compteur][position] = s.charAt(i);
        position++;
    else if(p.equals("/n")) {
        position = 0;
        compteur ++;
    }
}
return tab

【问题讨论】:

  • 数组在java中是固定大小的。您可以逐步创建更大的数组,在填充或使用列表之前确定第一遍中的维度。请不要链接到 png,而是将代码作为文本发布。
  • 您在请求矩阵的短语周围使用了引号。我们是否假设矩阵是真正的矩形(每行中的列数相同)......或者它可能是一个真正的“锯齿状数组”?那将是一个数组数组,其中每行中的元素数可能不同。

标签: java arrays string matrix


【解决方案1】:

@Lionel Ding 的解决方案当然会起作用,但值得一提的是,使用流可以说更优雅。但是,逻辑将保持不变 - 您将字符串拆分为 \n 字符,然后将每一行拆分为 ' ' 字符,将各个字符串解析为 ints 并将结果收集到 int[][]

private static int[][] toMatrix(String s) {
    return Arrays.stream(s.split("\n"))
                 .map(line -> Arrays.stream(line.split(" "))
                                    .mapToInt(Integer::parseInt).toArray())
                 .toArray(int[][]::new);
}

【讨论】:

  • 您好 Lionel 和 Mureinik,感谢您的回答。我有一个问题要问你们两个:莱昂内尔我读了你的答案,也许我不明白一点,或者你的代码可能不适用于每个字符串。我的意思是,当您说“int[][] out = new int[x.length][x[0].split("").length]”时,它仅适用于方阵吗?如果我的字符串是 "1 2\n 6 3 9" 怎么办?对于 Mureinik:我不理解流,你有介绍这个的视频或 API 吗?我是初学者谢谢!!!
【解决方案2】:

代码如下:

public static int[][] method(String s) {
    String[] x = s.split("\n");
    int[][] out = new int[x.length][x[0].split(" ").length];
    for (int i = 0; i < x.length; i++) {
        String[] y = x[i].split(" ");
        for (int j = 0; j < y.length; j++) {
            out[i][j] = Integer.parseInt(y[j]);
        }
    }
    return out;
}

在:

String s = "0 1\n2 3\n4 5"

输出:

int[][] array = [0 1],[2 3],[4 5]

上面的代码适用于方阵,但这里的代码适用于任何类型的矩阵! :

    public static int[][] method(String s) {
    String[] x = s.split("\n");
    int max = Integer.MIN_VALUE;
    for (String string : x) {
        int l = string.split(" ").length;
        max = l > max ? l : max;
    }
    int[][] out = new int[x.length][max];
    for (int i = 0; i < x.length; i++) {
        String[] y = x[i].split(" ");
        for (int j = 0; j < y.length; j++) {
            out[i][j] = Integer.parseInt(y[j]);
        }
    }
    return out;
}

在:

String s = "0 1\n2 3\n4 5 6\n1"

输出:

int[][] array = [0 1 0],[2 3 0],[4 5 6],[1 0 0]

【讨论】:

  • 谢谢你的回答,但莱昂内尔我读了你的回答,也许我不明白一点,或者你的代码可能不适用于每个字符串。我的意思是,当您说“int[][] out = new int[x.length][x[0].split("").length]”时,它仅适用于方阵吗?如果我的字符串是 "1 2\n 6 3 9" 怎么办?
  • 你说得对,我在原帖中添加了“非方阵”部分!
猜你喜欢
  • 2016-12-12
  • 2021-12-14
  • 1970-01-01
  • 2019-08-19
  • 2016-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-01
相关资源
最近更新 更多