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?
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.
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.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With