Program to demonstrate how to search or check for a word whether its in string or not.
Output of the program :
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 :
