Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through string array in Java

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.

This how far I have come:

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?

like image 335
ErikssonE Avatar asked Jul 15 '11 13:07

ErikssonE


People also ask

How do I iterate over an array of strings?

Iteration over a string array is done by using java for loop, or java for each loop. The code starts from index 0, and continues up to length – 1, which is the last element of the array.

How do I iterate through a string?

For loops with strings usually start at 0 and use the string's length() for the ending condition to step through the string character by character. String s = "example"; // loop through the string from 0 to length for(int i=0; i < s. length(); i++) { String ithLetter = s.

Are strings iterable in Java?

Many Java framework classes implement Iterable , however String does not. It makes sense to iterate over characters in a String , just as one can iterate over items in a regular array.


1 Answers

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);  } 
like image 72
Michal Avatar answered Sep 19 '22 18:09

Michal