【问题标题】:How do you split a string array [duplicate]你如何分割一个字符串数组[重复]
【发布时间】:2011-07-25 04:39:32
【问题描述】:

可能重复:
Grabbing a segment of an array in Java

我有一个可能包含 3、6、14 或 20 个元素的 String[]。我想每次处理来自 String[] 数组的 10 个元素。

(例如,对于 3 或 6,它将为 14 或 20 循环一次和两次)

【问题讨论】:

    标签: java


    【解决方案1】:

    您可以使用Arrays.copyOfRange 获取数组的子范围。

    【讨论】:

      【解决方案2】:

      假设String[] array,您是否正在寻找类似的东西:

      int pos = 0;
      while (pos + 10 < array.length) {
          // process array[pos] to array[pos + 9] here
          pos += 10;
      }
      // process array[pos] to array[array.length - 1] here
      

      【讨论】:

        【解决方案3】:

        使用 thsi 为每 10 个元素循环一个:

        int index = 0;
        while (index < array.length) do
        {
          // process
          index = index + 10;
        }
        

        【讨论】:

          【解决方案4】:
          String[] arr={"h","e","l","l","o"};
          List<String> li = Arrays.asList(arr);
          final int divideBy=2;
          for(int i=0;i<arr.length;i+=divideBy){
              int endIndex=Math.min(i+divideBy,arr.length);
              System.out.println(li.subList(i,endIndex)); 
          }
          

          【讨论】:

            【解决方案5】:

            两个嵌套循环:

                int[] nums = new int[14];
                // some initialization
                for (int i = 0; i < nums.length; i++) {
                    nums[i] = i;
                }
                // processing your array in chunks of ten elements
                for (int i = 0; i < nums.length; i += 10) {
                    System.out.println("processing chunk number " + 
                            (i / 10 + 1) + " of at most 10 nums");
                    for (int j = i ; j < 10 * (i + 1) && j < nums.length; j++) {
                        System.out.println(nums[j]);
                    }
                }
            

            输出是

            处理最多 10 个 nums 中的第 1 个块 0 1 2 3 4 5 6 7 8 9 处理最多 10 个 nums 中的第 2 个块 10 11 12 13

            我使用的是int[] 而不是String[],但它是一样的。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2014-12-11
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多