wood burning stoves*
The moose likes Java in General and the fly likes split the 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 » Java in General
Bookmark "split the string" Watch "split the string" New topic
Author

split the string

Pramod P Deore
Ranch Hand

Joined: Jul 15, 2008
Posts: 629

I have one string which contain delimiter suppose "?". Now I want to print a string which is separated by "?"
Suppose the String is
String str = "My?Name?Is?Pramod?Deore";
Now I want output as 5 string which are 1)My 2)Name 3)Is 4)Pramod 5)Deore

I had tried following program but it gives exception


Exception is as


Life is easy because we write the source code.....
Siddhesh Deodhar
Ranch Hand

Joined: Mar 05, 2009
Posts: 117
Try this
arr = str.split("\\?");
or use Pattern and Matcher.

Dont know why it dont works with simple
arr = str.split("?");

Would like to know why the above error comes.


Good, Better, Best, Don't take rest until, Good becomes Better, and Better becomes Best.
Sidd : (SCJP 6 [90%] )
Nevin kumar
Ranch Hand

Joined: Mar 15, 2008
Posts: 93
Dear Pramod,

It throws as exception because ? has special meaning in regular expressions.
? means Zero or one occurrence

change this line from arr = str.split("?"); to arr = str.split("\\?"); It

Reason:
String p = "?"; // regex sees this as the "?" metacharacter
String p = "\?"; // the compiler sees this as an illegal Java escape sequence
String p = "\\?"; // the compiler is happy, and regex sees a question mark, not a metacharacter

Siddhesh Deodhar
Ranch Hand

Joined: Mar 05, 2009
Posts: 117
Nevin kumar. I forgot that.
Pramod P Deore
Ranch Hand

Joined: Jul 15, 2008
Posts: 629

Thanks Nevin and Siddhesh .
Michael Angstadt
Ranch Hand

Joined: Jun 17, 2009
Posts: 273

You can also use the Pattern.quote() method to escape all special regular expression characters.



SCJP 6 || SCWCD 5
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: split the string
 
Similar Threads
Filtering Files
Thread Hangs at split method
why compile error in "Pattern.compile()?
Need help in stringObj.replaceAll()
How to use import java.util.regex.Pattern ?