假设我有一个 int 数组:
intarray = [2,3,5,7,8,8,9,3...]
如何在那里或其他地方加入前 5 个元素?
例如,我会有数字23578
or 35788
or 57889
...?
我正在尝试这样做,因为我需要相互比较数字
顺便说一句,我仍在寻找保留所有有关 java 语言的文档的好资源
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]
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);
}
}
输出:
23578
35788
57889
78893
如果您想使用库并在更高级别上工作,请尝试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);
StringUtils.join([1, 2, 3], null) = "123"