kavi
kavi

Reputation: 55

How to get only the last token using StringTokenizer in java

I want to get only the last token from stringTokenizer See below is my code:

String assetClasses = "Gold:Stocks:Fixed Income:Commodity:Interest Rates";
StringTokenizer token = new StringTokenizer(asseltClasses, ":");
while (token.hasMoreElements()) 
{
    System.out.println(token.nextToken());
}

My expected output is:

The last token is : Interest Rates

Upvotes: 0

Views: 11985

Answers (3)

Elyor Murodov
Elyor Murodov

Reputation: 1028

If you have to use StringTokenizer, just iterate over the elements, and take the last token while ignoring others:

String lastToken = null;
while(token.hasMoreElements()) {
    lastToken = token.nextToken();
}

Otherwise, in addition to other answers here, you can consider using StringUtils class from Apache Commons:

String lastToken = StringUtils.substringAfterLast(asseltClasses, ":");

Upvotes: 1

Bhuvan Rawal
Bhuvan Rawal

Reputation: 406

You can use split method in String class to achieve this, can get the last token without iterating through the whole loop.

private String getLastToken(String strValue, String splitter )  
{        
   String[] strArray = strValue.split(splitter);  
   return strArray[strArray.length -1];            
}     

Upvotes: 3

camickr
camickr

Reputation: 324118

Not very efficient to parse the entire string.

Instead you can use something like:

int index = assetClasses.lastIndexOf(...);
String token = assetClasses.substring(...);

Check out the String API for the parameters required for each of the methods.

Upvotes: 5

Related Questions