According to the documentation, the method parameter split
must be a regular expression.
And as in regular expressions the point has special meaning (means "any character"), he must be escaped with \
to lose this special meaning and be interpreted as the character itself .
:
String s = "0.101110";
String[] partes = s.split("\\.");
for (int i = 0; i < partes.length; i++) {
System.out.println("Elemento " + (i + 1) + ": " + partes[i]);
}
System.out.println("tamanho array: " + partes.length);
System.out.println("string: " + s);
Remembering that within a string the character \
should be written as \\
.
The exit is:
Element 1: 0
Element 2: 101110
array size: 2
string: 0.101110
Another alternative is to use the class java.util.regex.Pattern
, that has the method quote
, that makes the point escape (i.e., it does not need the \
, because the method returns a string already properly escaped):
String[] partes = s.split(Pattern.quote("."));
And a third alternative is to use \Q
and \E
. Basically, any character between the \Q
and \E
is interpreted literally, with no special meaning within the expression:
String[] partes = s.split("\\Q.\\E");
Both produce the same result as split("\\.")
(which, by the way, is the simplest solution - the two alternatives are useful when you have very large strings with several special characters, because there is less work than escaping one by one with \
).
Complementing, here explains why
split(".")
returns an empty array– hkotsubo