一次迭代一个数组2个项目 [英] Iterating through an array 2 items at a time

查看:160
本文介绍了一次迭代一个数组2个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似 {a,b,c,d} 的字符串数组。每两个连续的项是成对的,我想迭代数组,并能够将两个字符串一起考虑。目前我正在考虑使用循环和计数来计算我在迭代中的位置,但有更简单/更好的方法吗?

I have a string array that looks something like {"a","b","c","d"}. Each two consecutive items are pairs and I want to iterate through the array and be able to consider the two strings together. Currently I'm thinking of having a loop and a count to work out where I am in the iteration but is there a simpler/better way?

推荐答案

for (int i=0 ; i<a.length ; i+=2) {
    String first = a[i];
    String second = a[i+1];
    ...
}

如果数组由来电者提供,那么你可能想要处理a.length不均匀的情况。

If the array is provided by a caller, then you might want to handle the case where a.length is not even.

这篇关于一次迭代一个数组2个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆