0

I am trying to write a Java program to print preceding and succeeding of a known word in a text file.

For example Suppose I know a word "like"

a text file contains text like below Sam like chocolate and other stuff

I need to print Sam and chocolate which are preceding and succeeding the known word like. can anybody give a Java program for the above task.

Lion
  • 18,729
  • 22
  • 80
  • 110

2 Answers2

0

This is not a homework service, but a tip:
You're reading words, keep the previous word read in memory so you can print it if needed.

Using that, the solution should be trivial if you know how to read a text file and extract single words from its content.

jwenting
  • 5,505
  • 2
  • 25
  • 30
0

I won't give you the full code as this looks like homework and so you really should learn from it. I will give you some help.

First, look into reading the file into a string - How do I create a Java string from the contents of a file?. That should get you the text of the file in a string.

Next look at the .split method on String. It can split a string on any character, say a space " " character? http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split(java.lang.String)

Now you have an array of words in Strings. So just loop through the array looking for "like", simple string comparison, and print out the one before and after.

Easy. Hope that helps.

Community
  • 1
  • 1
Michael Allen
  • 5,712
  • 3
  • 38
  • 63
  • I have used Scanner class which can effectively read a text file and having lot of methods for searching operations.It was really useful . –  Jan 30 '13 at 10:21