Write a program How to search a word inside a string?


This Java program searches for a specific word "Computer" in a given string using the indexOf() method. Here's a breakdown of how the program works:

  • A string str is declared and initialized with the value "Tutor Joes Computer Education".
  • The indexOf() method is used to search for the index of the word "Computer" in the string str. If the word is found, the index of the first occurrence of the word is returned. If the word is not found, -1 is returned.
  • An if statement is used to check whether the returned index is equal to -1. If it is, then the word "Computer" is not found in the string, and a message "Computer Not Found" is printed to the console.
  • If the returned index is not equal to -1, then the word "Computer" is found in the string, and a message "Found Computer at Index X" is printed to the console, where X is the index of the first occurrence of the word "Computer" in the string.

Source Code

class Search_Word
{
	public static void main(String[] args)
	{
		String str = "Tutor Joes Computer Education";
		int in = str.indexOf("Computer");
		if(in == - 1)
		{
			System.out.println("Computer Not Found");
		}
		else
		{
			System.out.println("Found Computer at Index " + in);
		}
	}
}

Output

Found Computer at Index 11

Example Programs