This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes split string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "split string" Watch "split string" New topic
Author

split string

dale con
Ranch Hand

Joined: Apr 15, 2005
Posts: 93
Hello

I'm trying to split a string (delimited with a pipe)

String s = "this|is|an|example";
String [] results = s.split("|");

String a = results[0]; // here io expect to get 'this'
String b = results[1]; // here io expect to get 'is'

But i'm not gettiong what i expect to get

Can anyone tell mewhere i'm going wrong
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

The argument to split() is a regular expression, not just a plain old string. "|" is a special character in Java regular expressions; it represents "or", as in "this or that". Just an "|" alone ought to be an error, I'd think, but apparently it isn't; it seems to mean "nothing or nothing" in this context, so you're getting your string split at every character.

So, how to do this right? Escape the | with a backslash. You also have to protect the backslash with another backlash so that the Java compiler leaves it alone. So altogether, you want to use split("\\|") . This will work as you expect.


[Jess in Action][AskingGoodQuestions]
dale con
Ranch Hand

Joined: Apr 15, 2005
Posts: 93
Cheers

Forgot about ecasping the pipe
 
jQuery in Action, 2nd edition
 
subject: split string
 
Similar Threads
today's date & time
Best way to load data file into an array
Getting numeric data from VARCHAR2 type
HOW TO BREAK (TOKENIZE) A STRING ( like stringTokenizer in java)
String Reading