1

I've written the following code:

String[] arr = ((String) "asd.asd").split(".");

and arr=[]. Why?

St.Antario
  • 24,791
  • 31
  • 112
  • 278

4 Answers4

5

split takes a regular expression as an argument. "." in regular means "any character".

Instead, use:

 String[] arr = "asd.asd".split("\\.");

The backslashes escape the special meaning of the "." character in a regular expression.

http://docs.oracle.com/javase/tutorial/essential/regex/

ajp15243
  • 7,384
  • 1
  • 31
  • 38
khelwood
  • 52,115
  • 13
  • 74
  • 94
2

split() accepts a regex. you should escape the . use "\\." . In regex . is a special character (Meta character) which means match any character.

TheLostMind
  • 35,468
  • 12
  • 66
  • 99
1

You must double escape the ., otherwise the regular expression represents it as "any character".

Also, you don't need to cast "asd.asd" as String.

String[] arr = "asd.asd".split("\\.");
Mena
  • 46,817
  • 11
  • 84
  • 103
1

Because '.' is a special character. You need to escape it by writing it like this '\\.'

Le Ish Man
  • 451
  • 2
  • 4
  • 20
  • 2
    No, forward slashes really aren't going to help. And "special character" really doesn't describe what's going on. – Jon Skeet Sep 23 '14 at 14:05