• 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

split the string

 
Ranch Hand
Posts: 633
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Nevin kumar. I forgot that.
 
Pramod P Deore
Ranch Hand
Posts: 633
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Nevin and Siddhesh .
 
Ranch Hand
Posts: 282
Eclipse IDE PHP Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can also use the Pattern.quote() method to escape all special regular expression characters.

 
reply
    Bookmark Topic Watch Topic
  • New Topic