【问题标题】:Select element j in each column of an array in JAVA在JAVA中选择数组的每一列中的元素j
【发布时间】:2017-03-16 12:21:23
【问题描述】:

我有数组

String[] test_=new String[] {"a b c d", "f g h i","j k l s gf"};

现在我想创建另一个包含元素的数组

{"b d", "g i","k s"}

我该怎么做?

我已经设法将数组分隔成行使用

String split_test[] = null;
for (int j = 0 ; j <= 2 ; j++) {
      split_test=test_[j].split("\\s+");
      System.out.println(Arrays.toString(split_test));
}

但现在我想分开每一行,我尝试了解决方案 How to Fill a 2d array with a 1d array? 结合类似这样的 split_test=test_[j].split("\s+"),但是我一直没能解决。

另外,如果我按照他们说的做,我必须让数组 split_test 有许多特定的列,但我想要的是 split_test 的列的大小取决于数组 test_。例如,如果我想要一个包含元素 {"b d", "g i", "k s gf"}

String[][] split_test = new String[3][2];
for(int row = 0; row < split_test.length; row++) {
    for(int col = 0; col < split_test[row].length; col++) {
        split_test[row][col] = test_[row];/*I still don't understand how to use the split within the for*/
        System.out.println(split_test[row][col]);
    }
}

有没有更简单有效的方法?

谢谢

【问题讨论】:

  • 你想在test_ 上添加什么逻辑来从数组中读取项目?

标签: java arrays string vector split


【解决方案1】:

这是另一个。 您可以使用String 类的substring 方法。 或者使用split 方法返回的数组的索引。

    String output[] = new String[test_.length];
    String split_test[] = null;
    for (int j = 0; j < test_.length(); j++) {
        split_test = test_[j].split("\\s+");

        // use direct index
        // output2[j] = split_test[1] + " " + split_test[3];
        // or based on length
        output[j] = split_test[1] + " " + split_test[split_test.length - 2];
    }
    System.out.println(Arrays.toString(output));

输出:

b d
g i
k s

【讨论】:

    【解决方案2】:

    我使用了另一种同样有效的方法。我注意到您只采用不均匀的索引,因此我采用模数方法:

        String[] array = new String[] {"a b c d", "f g h i","j k l s gf"};
        String[] result = new String[array.length];
        for(int i = 0; i < array.length; i++) {
            String subresult = "";
            String[] array2 = array[i].split(" ");
            for(int j = 0; j < array2.length; j++) {
                if(j % 2 == 1)
                    subresult += array2[j] +" ";
            }
            result[i] = subresult.trim();
        }
    

    【讨论】:

      【解决方案3】:

      您应该使用二维数组,您可以通过以下方式创建一个:

      String[][] input=new String[][] {{"a","b","c","d"}, {"f","g","h","i"},{"j","k","l","s"}};
      

      然后您可以执行以下操作来检索{{"b","d"}, {"g","i"},{"k","s"}}

      String[][] output = new String[input.length][2];
      for(int i = 0; i<input.length; i++)
      {
        output[i] = new String[]{input[i][1],input[i][3]};
      }
      
      System.out.println(Arrays.deepToString(output));
      

      【讨论】:

        猜你喜欢
        • 2013-06-09
        • 2014-06-19
        • 1970-01-01
        • 1970-01-01
        • 2020-03-20
        • 2017-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多