yellow
yellow

Reputation: 455

How to split a string and see if its the last entry in the string?

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

Answers (4)

numX
numX

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

RAZ_Muh_Taz
RAZ_Muh_Taz

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

rohitvats
rohitvats

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

Adam
Adam

Reputation: 2279

Add stringList.add(s.pop()); after your loop.

Upvotes: 1

Related Questions