English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans cet exemple, nous allons apprendre à utiliser les méthodes contains() et indexOf() de Java pour vérifier si une chaîne contient une sous-chaîne.
Pour comprendre cet exemple, vous devriez comprendre ce qui suitProgrammation JavaThème :
class Main { public static void main(String[] args) { //Créer une chaîne de caractères String txt = "This is w"3codebox"; String str1 = "w3codebox"; String str2 = "Programming"; //Vérifier si le nom existe dans txt //Utiliser contains() boolean result = txt.contains(str1); if(result) { System.out.println(str1 + " appears in the string."); } else { System.out.println(str1 + " does not appear in the string."); } result = txt.contains(str2); if(result) { System.out.println(str2 + " appears in the string."); } else { System.out.println(str2 + " does not appear in the string."); } } }
Output results
w3codebox appears in the string. Programming does not appear in the string.
Dans cet exemple, nous avons trois chaînes txt, str1and str2。Ici, nous utilisons String decontains()Méthode pour vérifier la chaîne str1and str2S'il apparaît dans txt.
class Main { public static void main(String[] args) { //Créer une chaîne de caractères String txt = "This is w"3codebox"; String str1 = "w3codebox"; String str2 = "Programming"; //Check str1whether it exists in txt //using indexOf() int result = txt.indexOf(str1); if(result == -1) { System.out.println(str1 + " does not appear in the string."); } else { System.out.println(str1 + " appears in the string."); } //Check str2whether it exists in txt //using indexOf() result = txt.indexOf(str2); if(result == -1) { System.out.println(str2 + " does not appear in the string."); } else { System.out.println(str2 + " appears in the string."); } } }
Output results
w3codebox appears in the string. Programming does not appear in the string.
In this example, we usestring indexOf()method to find the string str1and str2In the position of txt. If the string is found, return the position of the string. Otherwise, return-1.