java guy
java guy

Reputation: 193

Java split method is not working properly?

This is my piece of code I want to split the string with $ symbol but the string doesn't getting spitted.

Here is my code:

   String str="first$third$nine%seventh";
   String s[]=str.split("$");
   System.out.println(s[0]);

The output is the whole string:

first$third$nine%seventh

Upvotes: 0

Views: 346

Answers (2)

kavi temre
kavi temre

Reputation: 1321

This is a very common thing in string class. Ans this has been already asked and answers are available in stackoverflow.

You should escape the regular expression symbol in split method. There are so many characters like $,?,*,^,+ which should be escaped while using as a parameter in split method.

Upvotes: 0

khelwood
khelwood

Reputation: 59095

split takes a regular expression as an argument. $ is a magic character in regex.

If you escape it with backslashes, it will be used as a normal character instead of a special regex character.

String s[]=str.split("\\$");

Upvotes: 7

Related Questions