Pin It

How to search or check for a word whether its in string or not through a Java program?

Program to demonstrate how to search or check for a word whether its in string or not.


package com.hubberspot.example;


public class SearchWordTest {

 public static void main(String[] args) {

  String line = "Hi ! ... Welcome to Hubberspot"
    +"We are Java professionals helping our students"
    +"in learning Java.";

  String key = "Hubberspot";

  System.out.println("-----------------------------------------------------");
  System.out.println("Method 1 to find key in String : Using contains() method of String ");
  System.out.println("-----------------------------------------------------");
  if(line.contains(key)) {
   System.out.println("Found the key " + key +" at the index "
     + line.indexOf(key));
  } 
  else {
   System.out.println("Cannot find " + key +" at any index");     
  }
  
  System.out.println("-----------------------------------------------------");
  System.out.println("Method 2 to find key in String : Using indexOf() method of String");
  System.out.println("-----------------------------------------------------");
  
  if(line.indexOf(key) != -1) {
   System.out.println("Found the key " + key +" at the index "
     + line.indexOf(key));
  } 
  else {
   System.out.println("Cannot find " + key +" at any index");     
  }
  
  key = "google";
  
  System.out.println("-----------------------------------------------------");
  System.out.println("Unsuccessful scenario when there is no key in the String");
  System.out.println("-----------------------------------------------------");
  
  if(line.contains(key)) {
   System.out.println("Found the key " + key +" at the index "
     + line.indexOf(key));
  } 
  else {
   System.out.println("Cannot find " + key +" at any index");     
  }
  
  System.out.println("-----------------------------------------------------");
  System.out.println("Unsuccessful scenario when there is no key in the String");
  System.out.println("-----------------------------------------------------");
  
  if(line.indexOf(key) != -1) {
   System.out.println("Found the key " + key +" at the index "
     + line.indexOf(key));
  } 
  else {
   System.out.println("Cannot find " + key +" at any index");     
  }
 }

}





Output of the program :


Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot