English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial Básico de Java

Controle de fluxo do Java

Array do Java

Java orientado a objetos (I)

Java orientado a objetos (II)

Java orientado a objetos (III)

Tratamento de Exceções Java

Lista (List) do Java

Fila (Queue) do Java

Conjunto Map do Java

Conjunto Set do Java

Entrada e saída (I do Java/O)

Reader do Java/Writer

Outros tópicos do Java

Uso e exemplo do método split() da String em Java

Java String (String) Methods

O método split() da String em Java divide a string no ponto especificado pela expressão regular e retorna um array de substrings.

A sintaxe do método split() da String

string.split(String regex, int limit)

parâmetros do split()

o método split() da string pode aceitar dois parâmetros:

  • regex - a string é dividida neste padrão regular (pode ser uma string)

  • limit (opcional)-especificar o número de substrings gerados

se não for passado o parâmetro limit, o split() retorna todas as substrings possíveis.

retorno do split()

  • retorna um array de substrings.

Atenção:se a expressão regular passada para split() for inválida, o método split() lança a exceção PatternSyntaxException.

Example1comparação de split() sem parâmetro limit

//Import arrays to convert arrays to strings
//Used to print arrays
import java.util.Arrays;
class Main {
    public static void main(String[] args) {
        String vowels = "a::b::c::d:e";
        //dividir a string no lugar "::"
        //armazenar o resultado em um array de strings
        String[] result = vowels.split("::");
        //Convert the array to a string and print
        System.out.println("result = " + Arrays.toString(result));
    }
}

Output Result

result = [a, b, c, d:e]

Aqui, dividimos a string no lugar ::. Como não foi passado o parâmetro limit, o array retornado contém todas as substrings.

com parâmetro limit

  • se o parâmetro limit for 0 ou negativo, o split() retorna um array contendo todas as substrings.

  • se o parâmetro limit for positivo (por exemplo, n), o split() retorna o valor máximo de substrings n.

Example2com parâmetro limit

//importar array, converter array para string
import java.util.Arrays;
class Main {
    public static void main(String[] args) {
        String vowels = "a:bc:de:fg:h";
        // divide a string no lugar ":"
        // limit = -2; O array contém todas as substrings
        String[] result = vowels.split(":", -2);
        System.out.println("retorna resultado quando limit for -2 retorna = " + Arrays.toString(result));
        // limit = 0; O array contém todas as substrings
        result = vowels.split(":", 0);
        System.out.println("retorna resultado quando limit for 0 = " + Arrays.toString(result));
        // limit = 2; O array pode conter no máximo2uma string substring
        result = vowels.split(":", 2);
        System.out.println("retorna resultado quando limit for 2 retorna = " + Arrays.toString(result));
        // limit = 4; O array pode conter no máximo4uma string substring
        result = vowels.split(":", 4);
        System.out.println("retorna resultado quando limit for 4 retorna = " + Arrays.toString(result));
        // limit = 10; O array pode conter no máximo10uma string substring
        result = vowels.split(":", 10);
        System.out.println("retorna resultado quando limit for 10 retorna = " + Arrays.toString(result));
    }
}

Output Result

retorna resultado quando limit for -2 retorna = [a, bc, de, fg, h]
retorna resultado quando limit for 0 = [a, bc, de, fg, h]
retorna resultado quando limit for 2 retorna = [a, bc:de:fg:h]
retorna resultado quando limit for 4 retorna = [a, bc:de:fg:h]
retorna resultado quando limit for 10 retorna = [a, bc, de, fg, h]

Atenção:O método passa a expressão regular como o primeiro parâmetro. Se precisar usar caracteres especiais, como \, |, ^, "*、+ such as, then these characters need to be escaped. For example, we need to use \\+ to split +.

Example3: split() splits the string at+at the character position

//Import arrays to convert arrays to strings
//Used to print arrays
import java.util.Arrays;
class Main {
    public static void main(String[] args) {
        String vowels = "a+e+f";
        //Split the string at the+" 处
        String[] result = vowels.split("\\+");
        //Convert the array to a string and print
        System.out.println("result = " + Arrays.toString(result));
    }
}

Output Result

result = [a, e, f]

Here, to be+at the split point of the string, we used \\+. This is because+It is a special character (with special meaning in regular expressions).

Java String (String) Methods