Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

How to Search a Word inside a String in Java



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

Using the indexOf() 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.

Example

This 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 0

Using 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.

Example

The 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
Advertisements