Search...
FAQs
Subscribe
Pie
FAQs
Recent topics
Flagged topics
Hot topics
Best topics
Search...
Search within Java in General
Search Coderanch
Advance search
Google search
Register / Login
Post Reply
Bookmark Topic
Watch Topic
New Topic
programming forums
Java
Mobile
Certification
Databases
Caching
Books
Engineering
Micro Controllers
OS
Languages
Paradigms
IDEs
Build Tools
Frameworks
Application Servers
Open Source
This Site
Careers
Other
Pie Elite
all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Campbell Ritchie
Jeanne Boyarsky
Ron McLeod
Paul Clapham
Liutauras Vilda
Sheriffs:
paul wheaton
Rob Spoor
Devaka Cooray
Saloon Keepers:
Stephan van Hulst
Tim Holloway
Carey Brown
Frits Walraven
Tim Moores
Bartenders:
Mikalai Zaikin
Forum:
Java in General
Use of String Tokeniser to get data after second occurrence of "_"
pendse anagha
Ranch Hand
Posts: 44
posted 18 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
Hello ,
Could someone point me to how I could get data that exists after the second
occurrence of the delimiter "_".
Here is what I have :
import java.util.StringTokenizer; public class Ex2 { public static void main(String[] args) { String sample = "lmn_a_b"; System.out.println("val = " + returnTokenizedVal(sample,2,"_")); } private static String returnTokenizedVal(String src,int indexedToken,String token){ StringTokenizer strTok = new StringTokenizer(src,token); int i = 0; String retVal = null; while(strTok.hasMoreTokens()){ i = i +1; if(i==indexedToken){ retVal = strTok.nextToken(); break; } } return retVal; } }
I always seem to get "lmn" when I want to return "b"
Also if I specify input
string
as "lmn_a" - would it be possible to return null or an empty string ?
Thanks ,
-anagha
Adam Vinueza
Ranch Hand
Posts: 76
posted 18 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
You're calling the nextToken method only once, which is why you get "lmn" instead of "b". Try something like this instead:
private static String returnTokenizedVal( String src, int indexedToken, String token ) { StringTokenizer strTok = new StringTokenizer( src, token ); int i = 0; String retVal, tmp; while ( strTok.hasMoreTokens() ) { tmp = strTok.nextToken(); if ( i++ == indexedToken ) { retVal = tmp; break; } } return retVal; }
That's my roommate. He's kinda weird, but he always pays his half of the rent. And he gave me this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
reply
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
Regarding string tokenizer
Memory leak while using String tokenizer
converting this to a prefix instead of a postfix calculator
Hi
empty tokens in String Tokenizer
More...