0

I have a string in following format:

CT-d0712728-867d-4cc4-bd0c-b2a679b8385f~#$~2012-10-16 02:13:27 PM

Can I use String.split("~#$~") or do I have to use StringTokenizer? I will have ONLY 2 parameters in above string, that's why I was trying to use String.Split("~#$~") but it doesn't seem to work.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Alex
  • 833
  • 3
  • 15
  • 28
  • similar question. http://stackoverflow.com/questions/8551489/how-to-split-the-string-using-this-special-character-in-java – Amareswar Oct 16 '12 at 18:35
  • What happened when you tried it? Did you capture the results into a `String[]`? – Makoto Oct 16 '12 at 18:35

5 Answers5

7

$ is special character in regex (it means "end of a line"). To make it simple literal you need to escape it, for example with

  • "\\$",
  • "[$]"
  • or using quotations "\\Q$\\E".
Pshemo
  • 122,468
  • 25
  • 185
  • 269
1

Since split() method takes the paremeters as Regex, and $ is special meta-character in Regex. You need to escape the $ sign: -

    System.out.println(str.split("~#\\$~")[0]);
    System.out.println(str.split("~#\\$~")[1]);
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
0

try

String s = "CT-d0712728-867d-4cc4-bd0c-b2a679b8385f~#$~2012-10-16 02:13:27 PM";

Arrays.toString(s.split("~#\\$~"))
banjara
  • 3,800
  • 3
  • 38
  • 61
0
String str = "CT-d0712728-867d-4cc4-bd0c-b2a679b8385f~#$~2012-10-16 02:13:27 PM";
String[] pieces = str.split("~#\\$~");
Tom G
  • 3,650
  • 1
  • 20
  • 19
0

you can do this using String.split(). No need to use StringTokenizer. See then below example.

String s="CT-d0712728-867d-4cc4-bd0c-b2a679b8385f~#$~2012-10-16 02:13:27 PM";
        String test[]=s.split("\\~\\#\\$\\~");
        System.out.println(test[0]);
        System.out.println(test[1]);

Let me know i you have any questions.

Sreedhar
  • 85
  • 5