O método Java String substring () extrai uma substring da string e a retorna.
A sintaxe do substring()
método é:
string.substring(int startIndex, int endIndex)
Aqui, string é um objeto da String
classe.
substring () Parâmetros
O substring()
método leva dois parâmetros.
- startIndex - o índice inicial
- endIndex (opcional) - o índice final
substring () Valor de retorno
O substring()
método retorna uma substring da string fornecida.
- A substring começa com o caractere no startIndex e se estende até o caractere no índice
endIndex - 1
. - Se o endIndex não for passado, a substring começará com o caractere no índice especificado e se estenderá até o final da string.

Observação: você obterá um erro se,
- startIndex / endIndex é negativo ou maior que o comprimento da string
- startIndex é maior que endIndex
Exemplo 1: substring Java () sem índice final
class Main ( public static void main(String() args) ( String str1 = "program"; // from the first character to the end System.out.println(str1.substring(0)); // program // from the 4th character to the end System.out.println(str1.substring(3)); // gram ) )
Exemplo 2: substring Java () com índice final
class Main ( public static void main(String() args) ( String str1 = "program"; // from 1st to the 7th character System.out.println(str1.substring(0, 7)); // program // from 1st to the 5th character System.out.println(str1.substring(0, 5)); // progr // from 4th to the 5th character System.out.println(str1.substring(3, 5)); // gr ) )
Se você precisar encontrar o índice da primeira ocorrência da substring especificada de uma determinada string, use o Java String indexOf ().