split does not return array with the string elements

Asked

Viewed 88 times

1

I’m having trouble using the method split, that is not returning me the array with the elements of the string.

public class Teste{


    public static void main (String[] args){

        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); 

    }
}

My exit is being:

array size: 0
string: 0.101110

1 answer

2


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 \).

  • 1

    Complementing, here explains why split(".") returns an empty array

Browser other questions tagged

You are not signed in. Login or sign up in order to post.