Méthode Java String lastIndexOf()
Exemple
Rechercher une chaîne pour la dernière occurrence de "planète":
String myStr = "Hello planet earth, you are a great planet.";
System.out.println(myStr.lastIndexOf("planet"));
Définition et utilisation
La lastIndexOf()
méthode renvoie la position de la dernière occurrence du ou des caractères spécifiés dans une chaîne.
Astuce : Utilisez la méthode indexOf pour renvoyer la position de la première occurrence du ou des caractères spécifiés dans une chaîne.
Syntaxe
Il existe 4 méthodes lastIndexOf() :
public int lastIndexOf(String str)
public int lastIndexOf(String str, int fromIndex)
public int lastIndexOf(int char)
public int lastIndexOf(int char, int fromIndex)
Valeurs des paramètres
Parameter | Description |
---|---|
str | A String value, representing the string
to search for |
fromIndex | An int value, representing the index position to start the search from. If omitted, the default value is the length of the string |
char | An int value, representing a single
character, e.g 'A', or a Unicode value |
Détails techniques
Retour: | Une int valeur, représentant l'index de la première occurrence du caractère dans la chaîne, ou -1 s'il n'apparaît jamais |
---|
Plus d'exemples
Exemple
Trouvez la dernière occurrence de "e" dans une chaîne, en commençant la recherche à la position 5 :
public class Main {
public static void main(String[] args) {
String myStr = "Hello planet earth, you are a great planet.";
System.out.println(myStr.lastIndexOf("e", 5));
}
}
❮ Méthodes de chaîne