//Program to calculate how many times a word occurs in a given string
import java.io.*; //for IOException, BufferedReader, InputStreamReader
class CountWord
{
public static void main(String args[]) throws IOException
{
System.out.println("Enter the string: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine(); //Gets a string from user
System.out.println("Enter the word to search for: ");
String word=br.readLine(); //Gets a string from user
int count=0,pos=0;
while(true)
{
pos=s.indexOf(word,pos);
if(pos==-1)
break;
else
{
count++;
pos++;
}
}
System.out.println(word+" occurs in given string for: "+count+" times");
}
}
By Er Gurpreet Singh,
Senior Software Engineer,
Sopra Steria India
Saturday, 13 June 2015
Program to calculate how many times a word occurs in a given string
Labels:
Java
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment