Reputation: 659
Suppose I have an int array:
intarray = [2,3,5,7,8,8,9,3...]
how to join the first 5 elements there or others?
for instance, I would have the numbers 23578
or 35788
or 57889
...?
I'm trying to do it because I need to compare the numbers with each other
by the way, I'm still looking for great source that keep all docs about java language
Upvotes: 1
Views: 5653
Reputation: 12843
public static void main(String[] args) {
int[] intarray = new int[] { 2, 3, 5, 7, 8, 8, 9, 3 };
for (int j = 0; j < intarray.length - 4; j++) {
String s = "";
for (int i = j; i < j + 5; i++) {
s = s + String.valueOf(intarray[i]);
}
int value = Integer.parseInt(s);
System.out.println(value);
}
}
Output:
23578
35788
57889
78893
Upvotes: 2
Reputation: 5916
If you want to use a library, and work at a higher level, try Guava.
int[] ary = {7,4,1,2,5,8,9,3};
Iterable<int[]> first5 = Iterables.limit(Lists.newArrayList(ary), 5);
String joined = Joiner.on("").join(first5);
Upvotes: 1
Reputation: 133072
pseudocode:
int frstNumber = 0;
for i = 0 to 4
firstNumber *= 10;
firstNumber += array[i];
nextNumber = firstNumber
for i = 5 to end of array
nextNumber = (nextNumber mod 10000) * 10 + array[i]
Upvotes: 2