Проверка наличия подстроки в строке на Java — методы contains и indexOf
В этой программе мы научимся проверять, содержит ли одна строка другую (подстроку).
Пример 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 is present in the string.
Programming is not present in the string.
В примере выше у нас три строки: 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 is present in the string.
Programming is not present in the string.
В этом примере мы использовали метод String.indexOf(), чтобы найти позицию строк str1 и str2 внутри txt. Если строка найдена, возвращается её позиция. Иначе возвращается -1.