开发者

How do you split a string array [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Grabbing a segment of an array in Java

I have a String[] which might contain 3, 6, 14 or 20 elements. I want to process 10 elements from the String[开发者_运维知识库] array each time.

(e.g. for 3 or 6 it will loop once and twice for 14 or 20)


You can use Arrays.copyOfRange to obtain subranges of your array.


Are you looking for something like this, assuming a 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


Use thsi to loop one for each 10 Elements:

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


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)); 
}


Two nested loops:

    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]);
        }
    }

Output is

processing chunk number 1 of at most 10 nums
0
1
2
3
4
5
6
7
8
9
processing chunk number 2 of at most 10 nums
10
11
12
13

I've used an int[] and not a String[], but it's the same.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜