
Write a program in java to find out the frequency of words in a sentence.
It is a simple java string program. Just split the sentence into a string array by split() method and create a resultent empty string. Now travel the string array and rejoin the stentence by replaceing the specefied word. Here we use the for each loop which is introduce in jdk1.5 version.
import java.util.*;
class ReplaceWord
{
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();
System.out.print("Enter the new word : ");
String newword=sc.nextLine();
String res="";
String []words=str.split(" "); //split the sentence into words
for (String word : words) {
if(word.equalsIgnoreCase(searchword))
{
res += newword + " ";
}
else
{
res += word + " ";
}
}
System.out.println("New Sentence will be " + res.trim());
}
}