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

Java-Grundlagen-Tutorial

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java-Exception-Verarbeitung

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input/output (I/)

Java Reader/Writer

Java other topics

Java String substring() usage and example

Java String (Zeichenkette) Methoden

The Java String substring() method extracts a substring from the string and returns it.

The syntax of substring() method is:

string.substring(int startIndex, int endIndex)

substring() parameters

The substring() method has two parameters.

  • startIndex - Start index

  • endIndex (Optional)-End index

The return value of substring()

The substring() method returns a substring from the given string.

  • The substring exists together with the character at startIndex and extends to the index endIndex - 1characters.

  • If endIndex is not passed, the substring exists together with the character at the specified index and extends to the end of the string.

The operation of the Java String substring() method

Note:If startIndex or endIndex is negative or greater than the length of the string, an error will occur. An error will also occur if startIndex is greater than endIndex.

Beispiel1:Java substring() ohne Endindex

class Main {
    public static void main(String[] args) {
        String str1 = "program";
        //von dem ersten Zeichen bis zum Ende
        System.out.println(str1.substring(0));  // program
        //von dem vierten Zeichen bis zum Ende
        System.out.println(str1.substring(3));  // gram
    }
}

Beispiel2:Java substring() mit Endindex

class Main {
    public static void main(String[] args) {
        String str1 = "program";
        //von dem ersten Zeichen bis zum siebten Zeichen
        System.out.println(str1.substring(0, 7));  // program
        //von der1bis zum5Zeichen
        System.out.println(str1.substring(0, 5));  // progr
        //von der4bis zum5Zeichen
        System.out.println(str1.substring(3, 5));  // gr
    }
}

Wenn Sie den ersten Treffer eines angegebenen Unterstrings im String suchen möchten, verwenden SieJava String indexOf() Methode

Java String (Zeichenkette) Methoden