Chercher un mot ou un caractère dans une chaîne de caractères | Java
Dans ce tutoriel nous allons découvrir comment chercher un mot ou un caractère dans une chaîne de caractères en Java.
Dans l’exemple suivant, nous allons utiliser la méthode indexOf() qui renvoie la position du première occurrence des caractères spécifiés dans une chaîne. Vous pouvez utilisez la méthode lastIndexOf() pour renvoyer la position de la dernière occurrence des caractères spécifiés dans une chaîne.
Exemple:
public class Main {
public static void main(String[] args) {
String str = "Welcome to WayToLearnX";
int index = str.indexOf("WayToLearnX");
if(index == - 1) {
System.out.println("Le mot WayToLearnX n'existe pas.");
} else {
System.out.println("Le mot WayToLearnX se trouve à l'index : "+ index);
}
}
}
public class Main {
public static void main(String[] args) {
String str = "Welcome to WayToLearnX";
int index = str.indexOf("WayToLearnX");
if(index == - 1) {
System.out.println("Le mot WayToLearnX n'existe pas.");
} else {
System.out.println("Le mot WayToLearnX se trouve à l'index : "+ index);
}
}
}
public class Main { public static void main(String[] args) { String str = "Welcome to WayToLearnX"; int index = str.indexOf("WayToLearnX"); if(index == - 1) { System.out.println("Le mot WayToLearnX n'existe pas."); } else { System.out.println("Le mot WayToLearnX se trouve à l'index : "+ index); } } }
Sortie:
Le mot WayToLearnX se trouve à l'index : 11