aspose file tools*
The moose likes Java in General and the fly likes Getting the Last token from a String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Getting the Last token from a String" Watch "Getting the Last token from a String" New topic
Author

Getting the Last token from a String

Prem Bhazee
Ranch Hand

Joined: Feb 18, 2006
Posts: 34
Hi Ranchers,

I have a string from which I need to get the last token and the token changes everytime based on the string value.I am planning to use String tokenizer with hasMoreTokens method. Haven't come with the code as of it. Is there any other ways of getting the last token of a string variable. Please let me know.

Thanks in advance
Bhazee
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3170
    
  10
Use String.split() and then just get the last element of the returned array.


Joanne
Prem Bhazee
Ranch Hand

Joined: Feb 18, 2006
Posts: 34
Hi

I am using String split to split my string.This is the method I have written.

strValue = "abc!$#cde!$#def"



But it returns the whole string and also I tried with "\\!$#" still same result.

Can you please help

Bhazee
Prem Bhazee
Ranch Hand

Joined: Feb 18, 2006
Posts: 34
Hi,
I tried "!\\$#" and it worked. My understanding is that $ is regular-expression constructs so that it had to be trailed with \\.

Just curious is this the correct reason.

Thanks
Bhazee
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36599
    
  16
I think you are correct, yes.

Lots more about regular expressions here. The $ is one of several "meta-characters."
Prabu Dhanapal
Greenhorn

Joined: Aug 12, 2011
Posts: 21
Try the simpler approach

String s = "Hello world again";
int i = s.lastIndexOf(' ');
String buffer = s.substring(i+1);
System.out.println(buffer);

The output will be: again
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36599
    
  16
Welcome to the Ranch
Yes, that approach would work.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Getting the Last token from a String
 
Similar Threads
StringTokenizer
K & B example Problem.
request.getParameter()
String Tokenizer
request.setAttribute in firefox