W tym przykładzie nauczymy się sprawdzać, czy ciąg zawiera podłańcuch przy użyciu metody zawiera () i indexOf () w Javie.
Aby zrozumieć ten przykład, należy znać następujące tematy dotyczące programowania w języku Java:
- Ciąg Java
- Podciąg ciągu Java ()
Przykład 1: Sprawdź, czy ciąg zawiera podciąg przy użyciu zawiera ()
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."); ) ) )
Wynik
Programiz jest obecny w ciągu. Brak programowania w ciągu.
W powyższym przykładzie mamy trzy ciągi tekstowe txt, str1 i str2. Tutaj użyliśmy metody String zawiera (), aby sprawdzić, czy ciągi str1 i str2 są obecne w txt.
Przykład 2: Sprawdź, czy ciąg zawiera podciąg za pomocą 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."); ) ) )
Wynik
Programiz jest obecny w ciągu. Brak programowania w ciągu.
W tym przykładzie użyliśmy metody String indexOf (), aby znaleźć pozycję łańcuchów str1 i str2 w txt. Jeśli ciąg zostanie znaleziony, zwracana jest jego pozycja. W przeciwnym razie zwracane jest -1 .