问题描述
我有包含一些组件的 String 数组,这个数组有 5 个组件,它有时会有所不同.我想做的是遍历该数组并获取第一个组件和该组件旁边的组件.因此,第一次我将获得第一个组件和第 2 个组件,第二次将获得数字 2 和 3,第三次获得数字 3 和 4...依此类推,直到您获得最后一个组件.
I have String array with some components, this array has 5 components and it vary some times. What I would like to do is to iterate through that array and get the first component and the component next to that one. So the first time I would get the component number one and the component number 2, the second time would get the number 2 and 3, the third time number 3 and 4... And so on until you get to the last component.
这是我走了多远:
String[] elements = { "a", "a","a","a" };
for( int i = 0; i <= elements.length - 1; i++)
{
// get element number 0 and 1 and put it in a variable,
// and the next time get element 1 and 2 and put this in another variable.
}
我怎样才能做到这一点?
How can I accomplish this?
推荐答案
你可以做一个 增强循环(对于java 5及更高版本)用于数组元素的迭代:
You can do an enhanced for loop (for java 5 and higher) for iteration on array's elements:
String[] elements = {"a", "a", "a", "a"};
for (String s: elements) {
//Do your stuff here
System.out.println(s);
}
这篇关于遍历Java中的字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!