To search for a word inside a string in Java, we can use different methods. The following are the methods to search for a word inside a string
Using the indexOf() method
Using the contains() method
The indexOf() method returns a numerical value representing the index of the first character of the substring that matches within the string. If the substring is not found, it returns -1. It is also true that the method is case-sensitive and can be used to search for both individual characters or a group of characters (substring) within a string.
ExampleThis example shows how we can search a word within a String object using indexOf() method which returns a position index of a word within the string if found. Otherwise it returns -1.
public class SearchStringEmp{ public static void main(String[] args) { String strOrig = "Hello readers"; int intIndex = strOrig.indexOf("Hello"); if(intIndex == - 1) { System.out.println("Hello not found"); } else { System.out.println("Found Hello at index " + intIndex); } } }Output
Found Hello at index 0Using the contains() method
The contains() method checks whether a string contains a particular sequence of characters. It returns true if the sequence is found within the string, and false otherwise. This method is case-sensitive and is typically used to verify whether a substring is present in a larger string.
ExampleThe following example shows how we can search a word within a String object
public class HelloWorld { public static void main(String[] args) { String text = "The cat is on the table"; System.out.print(text.contains("the")); } }Output
true
java_strings.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4