How to check if String Contains Specific word in Java


In this example we will show how to search a word within a String object using indexOf method in Java.

Source Code

package com.beginner.examples;

public class SearchString {

	public static void main(String[] args) {
		
		String string  = "HelloWorld";
		
		/*
		 * To search a particular word Java String use method indexOf().
		 */
		int result = string.indexOf("Hello");
		
		if(result == - 1) {
			System.out.println("Hello not found");
		}else {
			System.out.println("Found Hello at index " + result); 
		}
		
		/*
		 * To search a particular word after particular position Java String use method indexOf(String word, int position).
		 */
		int positionIndex = string.indexOf("World",3);
		System.out.println("Index of Hello after 11 is " + positionIndex);

	}

}

Output:

Found Hello at index 0
Index of Hello after 11 is 5
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments