What are search for a String in java?
How to search a word inside a string?
Here is the example that 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 SearchStringEmployee{
public static void main(String[] args) {
String strOrig = "Hello all employees";
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 0
Here we can see, Whether a word exist within a String object.
public class HelloWorldExample {
public static void main(String[] args) {
String text = "The mouse is on the Chair";
System.out.print("Text Exist : "+text.contains("the"));
}
}
Output
Text Exist : true
Recent Comments