Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

split the string

 
Pramod P Deore
Ranch Hand
Posts: 632
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Siddhesh Deodhar
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Nevin kumar
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nevin kumar. I forgot that.
 
Pramod P Deore
Ranch Hand
Posts: 632
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Nevin and Siddhesh .
 
Michael Angstadt
Ranch Hand
Posts: 277
Eclipse IDE Java PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can also use the Pattern.quote() method to escape all special regular expression characters.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic