Introduction
In this blog, we will learn how to check string contains a specific word or not. We are going to use contains method to perform this task.
contains() Method
This method returns true if a sequence of characters is present in the string otherwise it will return false.
Implementation
import java.util.*;
public class StringExample {
public static void main(String args[]) {
// Example 1
String str1 = "How are you";
String word1 = "are";
System.out.println("Given string is " + str1);
if (str1.contains(word1)) {
System.out.println(word1 + " is present in string");
} else {
System.out.println(word1 + " is not present in string");
}
// Example 2
String str2 = "The Key to happiness is the reduction of desires";
String word2 = "happiness";
System.out.println("Given string is " + str2);
if (str2.contains(word2)) {
System.out.println(word2 + " is present in string");
} else {
System.out.println(word2 + " is not present in string");
}
}
}
Output
Conclusion
In this blog, we have seen how to check if a string contains a specific word or not. Thanks for reading and I hope you liked it. If you have any suggestions or queries about this blog, please share your thoughts. You can read my other blog and articles by clicking here.
Happy learning, friends!