English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In questo esempio, impareremo a utilizzare i metodi contains() e indexOf() di Java per verificare se una stringa contiene una sottostringa.
Per comprendere questo esempio, dovresti conoscere i seguentiProgrammazione JavaArgomento:
class Main { public static void main(String[] args) { //创建一个字符串 String txt = "This is w3codebox"; String str1 = "w3codebox"; String str2 = "Programming"; //Verifica se esiste il nome in txt //使用 contains() boolean result = txt.contains(str1); if(result) { System.out.println(str1 + " è presente nella stringa."); } else { System.out.println(str1 + " "). } result = txt.contains(str2); if(result) { System.out.println(str2 + " è presente nella stringa."); } else { System.out.println(str2 + " non è presente nella stringa."); } } }
Risultato di output
w3codebox è presente nella stringa. Programming non è presente nella stringa.
Nell'esempio sopra, abbiamo tre stringhe txt, str1 e str2. Qui, usiamo la String dicontains()Metodo per verificare se le stringhe str1 e str2 appaiono in txt.
class Main { public static void main(String[] args) { //创建一个字符串 String txt = "This is w3codebox"; String str1 = "w3codebox"; String str2 = "Programming"; //检查str1是否存在于txt中 //Usa indexOf() int result = txt.indexOf(str1); if(result == -1) { System.out.println(str1 + " "). } else { System.out.println(str1 + " è presente nella stringa."); } //Controlla se str2 esiste nel txt //Usa indexOf() result = txt.indexOf(str2); if(result == -1) { System.out.println(str2 + " non è presente nella stringa."); } else { System.out.println(str2 + " è presente nella stringa."); } } }
Risultato di output
w3codebox è presente nella stringa. Programming non è presente nella stringa.
In questo esempio, usiamoindexOf() della stringaMetodo per trovare la posizione delle stringhe str1 e str2 nel file txt. Se la stringa viene trovata, restituisce la posizione della stringa. Altrimenti, restituisce -1.