| 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: 3011
|
|
|
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: 32654
|
|
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: 14
|
|
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: 32654
|
|
Welcome to the Ranch
Yes, that approach would work.
|
 |
 |
|
|
subject: Getting the Last token from a String
|
|
|