Write a Java Program to Check if a string contains a substring

Java Program to Check if a string contains a substring

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Check if a string contains a substring
Java Program to Check if a string contains a substring

Write a Java Program to Check if a string contains a substring

PROGRAM:Java Program to Check if a string contains a substring

/*Java Program to Check if a string contains a substring*/

1: Check if a string contains a substring using 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.”);
}
}
}

2: Check if a string contains a substring using 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.”);
}
}
}


		

Leave a Reply

Your email address will not be published. Required fields are marked *