1

I've written the following code:

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

and arr=[]. Why?

St.Antario
  • 26,175
  • 41
  • 130
  • 318

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,704
  • 1
  • 32
  • 38
khelwood
  • 55,782
  • 14
  • 81
  • 108
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,966
  • 12
  • 68
  • 104
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
  • 47,782
  • 11
  • 87
  • 106
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