Metóda Java String substring () extrahuje podreťazec z reťazca a vráti ho.
Syntax substring()
metódy je:
string.substring(int startIndex, int endIndex)
Reťazec je tu predmetom String
triedy.
podreťazec () parametre
substring()
Metóda má dva parametre.
- startIndex - začiatočný index
- endIndex (voliteľné) - koncový index
návratová hodnota substring ()
substring()
Metóda vracia podreťazec z daného reťazca.
- Podreťazec začína znakom v parametri startIndex a rozširuje sa na znak v indexe
endIndex - 1
. - Ak endIndex nie je odovzdaný, podreťazec začína znakom v zadanom indexe a siaha až na koniec reťazca.

Poznámka: Zobrazí sa chyba, ak
- startIndex / endIndex je záporný alebo väčší ako dĺžka reťazca
- startIndex je väčší ako endIndex
Príklad 1: Podreťazec Java () bez koncového indexu
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 ) )
Príklad 2: Podreťazec Java () S koncovým indexom
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 ) )
Ak potrebujete nájsť index prvého výskytu zadaného podreťazca z daného reťazca, použite Java String indexOf ().