It is a simple java string program. Just split the sentence into a string array by split() method and search the specified word in the array by using the equals() method of the java string class. Here we use the for each loop which is introduce in jdk1.5 version.
import java.util.*;
class FindWord
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a String:");
String str=sc.nextLine();
System.out.print("Enter the word you want to search : ");
String searchword=sc.nextLine();
String []words=str.split(" "); //split the sentence into words
int c=0;
for (String word : words) {
if(word.equals(searchword)){
c++;
}
}
System.out.println("The word " + searchword + " Found " + c + " Times.");
}
}
import java.util.*;
class FindWord
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a String:");
String str=sc.nextLine();
System.out.print("Enter the word you want to search : ");
String searchword=sc.nextLine();
String []words=str.split(" "); //split the sentence into words
int c=0;
for (String word : words) {
if(word.toLowerCase().equals(searchword.toLowerCase())){
c++;
}
}
System.out.println("The word " + searchword + " Found " + c + " Times.");
}
}
import java.util.*;
class FindWord
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a String:");
String str=sc.nextLine();
System.out.print("Enter the word you want to search : ");
String searchword=sc.nextLine();
String []words=str.split(" "); //split the sentence into words
int c=0;
for (String word : words) {
if(word.equalsIgnoreCase(searchword)){
c++;
}
}
System.out.println("The word " + searchword + " Found " + c + " Times.");
}
}