В этом примере мы научимся проверять, содержит ли строка подстроку, используя методы contains () и indexOf () в Java.
Чтобы понять этот пример, вы должны знать следующие темы программирования Java:
- Строка Java
- Подстрока Java String ()
Пример 1. Проверьте, содержит ли строка подстроку, используя contains ()
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 contains (), чтобы проверить, присутствуют ли строки 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 .