Jhii
Jhii

Reputation: 137

Is there a way to check if there is a next element on a String array?

I have a string and I split it into word by word

String s = "Apple Orange Banana Grapes";
String s2[] = s.split("\\s+");

s value is changing that's why I can't be sure how many elements on s2 can be made. Is there a way to check if there is still a next element on s2?

Example:

String s = "Pencil Eraser Pen";
String s2[] = s.split("\\s+");

As you can see the s now has 3 words compared to the other example therefore s2[] now has 3 elements. The next element of s2[0], s2[1], exists but the next element of s2[2] does not exist. I'm using Java by the way.

Upvotes: 2

Views: 2706

Answers (2)

The Obscure Question
The Obscure Question

Reputation: 1174

You can check to see if the index is out of the range of the array. You can find the length of the array by accessing the .length property of a String[].

Therefore, the code that you would use if i holds the index in the array (e.g. s2[i]) is if (i < s2.length - 1).

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521103

I think the construct you are seeking is a for loop. You can iterate over the array you obtain from splitting the fruit string by whitespace.

String s = "Apple Orange Banana Grapes";
String s2[] = s.split("\\s+");
for (String fruit : s2) {
    System.out.println(fruit);
}

Output:

Apple
Orange
Banana
Grapes

Upvotes: 1

Related Questions