Java String split ()

O método Java String split () divide a string na regex especificada e retorna uma matriz de substrings.

A sintaxe do split()método string é:

 string.split(String regex, int limit)

Aqui, string é um objeto da Stringclasse.

Parâmetros split ()

O split()método da string pode ter dois parâmetros:

  • regex - a string é dividida neste regex (podem ser strings)
  • limit (opcional) - controla o número de substrings resultantes

Se o limitparâmetro não for passado, split()retorna todas as substrings possíveis.

split () Valor de retorno

  • retorna uma matriz de substrings

Observação: se a expressão regular passada split()for inválida, o split()método gerará uma PatternSyntaxExpressionexceção.

Exemplo 1: split () sem parâmetro de limite

 // importing Arrays to convert array to string // used for printing arrays import java.util.Arrays; class Main ( public static void main(String() args) ( String vowels = "a::b::c::d:e"; // splitting the string at "::" // storing the result in an array of strings String() result = vowels.split("::"); // converting array to string and printing it System.out.println("result = " + Arrays.toString(result)); ) )

Resultado

 resultado = (a, b, c, d: e)

Aqui, dividimos a corda em ::. Como o limitparâmetro não é passado, a matriz retornada contém todas as substrings.

split () Com parâmetro de limite

  • Se o limitparâmetro for 0 ou negativo, split()retorna uma matriz contendo todas as substrings.
  • Se o limitparâmetro for positivo (digamos n), split()retorna o máximo de nsubstrings.

Exemplo 2: split () com parâmetro de limite

 // importing Arrays to convert array to string import java.util.Arrays; class Main ( public static void main(String() args) ( String vowels = "a:bc:de:fg:h"; // splitting array at ":" // limit is -2; array contins all substrings String() result = vowels.split(":", -2); System.out.println("result when limit is -2 = " + Arrays.toString(result)); // limit is 0; array contains all substrings result = vowels.split(":", 0); System.out.println("result when limit is 0 = " + Arrays.toString(result)); // limit is 2; array contains a maximum of 2 substrings result = vowels.split(":", 2); System.out.println("result when limit is 2 = " + Arrays.toString(result)); // limit is 4; array contains a maximum of 4 substrings result = vowels.split(":", 4); System.out.println("result when limit is 4 = " + Arrays.toString(result)); // limit is 10; array contains a maximum of 10 substrings result = vowels.split(":", 10); System.out.println("result when limit is 10 = " + Arrays.toString(result)); ) )

Resultado

 resultado quando o limite é -2 = (a, bc, de, fg, h) resultado quando o limite é 0 = (a, bc, de, fg, h) resultado quando o limite é 2 = (a, bc: de: fg: h) resultado quando o limite é 4 = (a, bc, de, fg: h) resultado quando o limite é 10 = (a, bc, de, fg, h)

Nota: O método split () leva regex como o primeiro argumento. Se você precisa usar caracteres especiais, tais como: , |, ^, *, +etc, você precisa escapar esses personagens. Por exemplo, precisamos usar \+para dividir em +.

Exemplo 3: split () no caractere +

 // importing Arrays to convert array to string // used for printing arrays import java.util.Arrays; class Main ( public static void main(String() args) ( String vowels = "a+e+f"; // splitting the string at "+" String() result = vowels.split("\+"); // converting array to string and printing it System.out.println("result = " + Arrays.toString(result)); ) )

Resultado

 resultado = (a, e, f)

Aqui, para dividir uma string +, usamos \+. É porque +é um caractere especial (tem um significado especial em expressões regulares).

Artigos interessantes...