Reputation: 455
I have a string and would like to split every sub string and add it to a stack, except for the last sub string to be added to a list.
String keysFromString = One|Two|Three;
Stack<String> s = new Stack<String>();
List <String> stringList = new ArrayList<String>();
if (keysFromString .contains("|")) {
String[] keys = keysFromString .split("|");
for (String key : keys) {
s.add(key)
}
}
Here I want One, Two in stack and Three in list, but I am not sure as how to identify and add the last entry to list as the given string may contain variable number of sub strings.
Upvotes: 0
Views: 51
Reputation: 850
using :
for (int i= 0; i<keys.length -1; i++) {
s.add(keys[i]);
}
you will not add the last element in the array
using keys.length
, you will get the length of the array which is a property. you can use this to iterate over the array, excluding the last item :i<keys.length - 1
. This cannot be done using the for (String key : keys)
technique.
P.S. keys.length()
does not exist as length is a property not a method
Upvotes: 0
Reputation: 4099
String keysFromString = "One|Two|Three";
Stack<String> s = new Stack<String>();
List <String> stringList = new ArrayList<String>();
if (keysFromString .contains("|"))
{
String[] keys = keysFromString .split("|");
//grab all but the last string in keys and add it to stack (s)
for (int i = 0; i < keys.length - 1; i++)
{
s.add(keys[i])
}
//add the last string from the split method to the stringList
stringList.add(keys[keys.length - 1]);
}
Upvotes: 1
Reputation: 1851
You can replace your current loop:
for (String key : keys) {
s.add(key)
}
with:
for (int i = 0; i < keys.length - 1; i++) {
s.add(keys[i]);
}
Upvotes: 0