English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Contrôle de flux Java

Java tableau

Java orienté objet (I)

Java orienté objet (II)

Java orienté objet (III)

Gestion des exceptions Java

Java Liste (List)

Java Queue (file d'attente)

Java Map collection

Java Set collection

Java entrée/sortie (I/O)

Java Reader/Writer

Autres sujets Java

Programme Java pour vérifier si une chaîne contient une sous-chaîne

    Java instance in full

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 :

Exemple1:Utiliser contains() pour vérifier si une chaîne contient une sous-chaîne

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.

Exemple2:Utiliser indexOf() pour vérifier si une chaîne contient une sous-chaîne

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.

Java instance in full