• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Getting the Last token from a String

 
Prem Bhazee
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3742
16
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use String.split() and then just get the last element of the returned array.
 
Prem Bhazee
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49849
70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you are correct, yes.

Lots more about regular expressions here. The $ is one of several "meta-characters."
 
Prabu Dhanapal
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49849
70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch
Yes, that approach would work.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic