/* related posts with thumb nails */

A program to read a text and count all the occurrences of a given word. Also, display their positions.:

import java.io.*;

class TextSearch

{

public static void main(String as[]) throws Exception

{

InputStreamReader isr=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(isr);

int i=0,count=0;

String text="",s="";

System.out.println("Enter Text:(press ENTER twice to stop)\n");

s=br.readLine();

while(s.length()!=0)

{

text+=s;

s=br.readLine();

}

System.out.println("Enter search word:");

s=br.readLine();

while(true)

{

i=text.indexOf(s,i);

if(i==-1) break;

System.out.println("Word found at position:"+i);

count++;

i+=s.length();

}

System.out.println("Number of occurrences of given word:"+count);

}

}

/* Output: */

Enter Text:(press ENTER twice to stop)

Hello hi , hi again

hi nice to see you

Enter search word:hi

Word found at position:6

Word found at position:11

Word found at position:19

Number of occurrences of given word:3

Related Topics:

0 comments:

Post a Comment