Πρόγραμμα Java για να ελέγξετε εάν μια συμβολοσειρά περιέχει ένα υπόστρωμα

Σε αυτό το παράδειγμα, θα μάθουμε να ελέγξουμε αν μια συμβολοσειρά περιέχει ένα substring χρησιμοποιώντας τη μέθοδο περιέχει () και indexOf () στην Java.

Για να κατανοήσετε αυτό το παράδειγμα, θα πρέπει να γνωρίζετε τις ακόλουθες εφαρμογές προγραμματισμού Java:

  • Συμβολοσειρά Java
  • Υποδομή συμβολοσειράς Java ()

Παράδειγμα 1: Ελέγξτε εάν μια συμβολοσειρά περιέχει ένα υπόστρωμα χρησιμοποιώντας περιέχει ()

 class Main ( public static void main(String() args) ( // create a string String txt = "This is Programiz"; String str1 = "Programiz"; String str2 = "Programming"; // check if name is present in txt // using contains() boolean result = txt.contains(str1); if(result) ( System.out.println(str1 + " is present in the string."); ) else ( System.out.println(str1 + " is not present in the string."); ) result = txt.contains(str2); if(result) ( System.out.println(str2 + " is present in the string."); ) else ( System.out.println(str2 + " is not present in the string."); ) ) )

Παραγωγή

Το Programiz υπάρχει στη συμβολοσειρά. Ο προγραμματισμός δεν υπάρχει στη συμβολοσειρά.

Στο παραπάνω παράδειγμα, έχουμε τρία συμβολοσειρά txt, str1 και str2. Εδώ, χρησιμοποιήσαμε τη μέθοδο String περιέχει () για να ελέγξουμε εάν οι συμβολοσειρές str1 και str2 υπάρχουν στο txt.

Παράδειγμα 2: Ελέγξτε αν μια συμβολοσειρά περιέχει ένα υπόστρωμα χρησιμοποιώντας το indexOf ()

 class Main ( public static void main(String() args) ( // create a string String txt = "This is Programiz"; String str1 = "Programiz"; String str2 = "Programming"; // check if str1 is present in txt // using indexOf() int result = txt.indexOf(str1); if(result == -1) ( System.out.println(str1 + " not is present in the string."); ) else ( System.out.println(str1 + " is present in the string."); ) // check if str2 is present in txt // using indexOf() result = txt.indexOf(str2); if(result == -1) ( System.out.println(str2 + " is not present in the string."); ) else ( System.out.println(str2 + " is present in the string."); ) ) )

Παραγωγή

Το Programiz υπάρχει στη συμβολοσειρά. Ο προγραμματισμός δεν υπάρχει στη συμβολοσειρά.

Σε αυτό το παράδειγμα, χρησιμοποιήσαμε τη μέθοδο String indexOf () για να βρούμε τη θέση των συμβολοσειρών str1 και str2 σε txt. Εάν βρεθεί η συμβολοσειρά επιστρέφεται η θέση της συμβολοσειράς. Διαφορετικά, επιστρέφεται το -1 .

ενδιαφέροντα άρθρα...