How to parse for words in a string for a specific word in java?


There are various methods in Java using which you can parse for words in a string for a specific word. Here we are going to discuss 3 of them.

The contains() method

The contains() method of the String class accepts a sequence of characters value and verifies whether it exists in the current String. If found it returns true else, it returns false.

Example

 Live Demo

import java.util.StringTokenizer;
import java.util.regex.Pattern;
public class ParsingForSpecificWord {
   public static void main(String args[]) {
      String str1 = "Hello how are you, welcome to Tutorialspoint";
      String str2 = "Tutorialspoint";
      if (str1.contains(str2)){
         System.out.println("Search successful");
      } else {
         System.out.println("Search not successful");
      }
   }
}

Output

Search successful

The indexOf() method

The indexOf() method of the String class accepts a string value and finds the (starting) index of it in the current String and returns it. This method returns -1 if it doesn’t find the given string in the current one.

Example

 Live Demo

public class ParsingForSpecificWord {
   public static void main(String args[]) {
      String str1 = "Hello how are you, welcome to Tutorialspoint";
      String str2 = "Tutorialspoint";
      int index = str1.indexOf(str2);
      if (index>0){
         System.out.println("Search successful");
         System.out.println("Index of the word is: "+index);
      } else {
         System.out.println("Search not successful");
      }
   }
}

Output

Search successful
Index of the word is: 30

The StringTokenizer class

Using the StringTokenizer class, you can divide a String into smaller tokens based on a delimiter and traverse through them. Following example tokenizes all the words in the source string and compares each word of it with the given word using the equals() method.

Example

 Live Demo

import java.util.StringTokenizer;
public class ParsingForSpecificWord {
   public static void main(String args[]) {
      String str1 = "Hello how are you welcome to Tutorialspoint";
      String str2 = "Tutorialspoint";
      //Instantiating the StringTookenizer class
      StringTokenizer tokenizer = new StringTokenizer(str1," ");
      int flag = 0;
      while (tokenizer.hasMoreElements()) {
         String token = tokenizer.nextToken();
         if (token.equals(str2)){
            flag = 1;
         } else {
            flag = 0;
         }
      }
      if(flag==1)
         System.out.println("Search successful");
      else
         System.out.println("Search not successful");
   }
}

Output

Search successful

Updated on: 11-Oct-2019

543 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements