English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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)
La méthode substring() a deux paramètres.
startIndex - Index de début
endIndex (Optionnel)-Index de fin
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.
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.
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 } }
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。