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

Tutoriel de base Java

Contrôle de flux Java

Java Tableau

Java Programmation orientée objet (I)

Java Programmation orientée objet (II)

Java Programmation orientée objet (III)

Gestion des exceptions Java

Java Liste (List)

Java Queue (file d'attente)

Java Map collection

Java Set collection

Java Entrée/Sortie (I/O)

Java Reader/Writer

Autres sujets Java

Utilisation et exemple de la méthode Java String substring()

Java String (string) methods

La méthode Java String substring() extrait une sous-chaîne de la chaîne et la retourne.

La syntaxe de la méthode substring() est :

string.substring(int startIndex, int endIndex)

Paramètres de substring()

La méthode substring() a deux paramètres.

  • startIndex - Index de début

  • endIndex (Optionnel)-Index de fin

Retour de la valeur de substring()

La méthode substring() retourne une sous-chaîne à partir de la chaîne donnée.

  • La sous-chaîne commence au caractère à l'indice startIndex et s'étend jusqu'à l'indice endIndex - 1des caractères.

  • Si endIndex n'est pas passé, la sous-chaîne commence au caractère à l'indice spécifié et s'étend jusqu'à la fin de la chaîne.

Fonctionnement de la méthode Java String substring()

Attention :Si startIndex ou endIndex est négatif ou supérieur à la longueur de la chaîne, une erreur se produira. Si startIndex est supérieur à endIndex, une erreur se produira également.

Example1:Without ending index Java substring()

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 fourth character to the end
        System.out.println(str1.substring(3));  // gram
    }
}

Example2:With ending index Java substring()

class Main {
    public static void main(String[] args) {
        String str1 = "program";
        //from the first character to the seventh character
        System.out.println(str1.substring(0, 7));  // program
        //from the1to the5a character
        System.out.println(str1.substring(0, 5));  // progr
        //from the4to the5a character
        System.out.println(str1.substring(3, 5));  // gr
    }
}

If you need to find the index of the first occurrence of the specified substring in the given string, please useJava String indexOf() method

Java String (string) methods