Nuwanda Nuwanda - 1 year ago 62
Java Question

how to find i of a token in an array[i]

So, I've found a word in a document and print the line in which the word is present like this:

say example file contains : "The quick brown fox jumps over the lazy dog.Jackdaws love my big sphinx of quartz."

FileInputStream fstream = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while((strLine = br.readLine()) != null){
//check to see whether testWord occurs at least once in the line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());

//get the line, and parse its words into a String array
String[] lineWords = strLine.split("\\s+");

for(int i=0;i<lineWords.length;i++){
System.out.print(lineWords[i]+ ' ');


And if I search for 'fox' , then linewords[] will contain tokens from the first sentence. and linewords[3] = fox. To print the color of the fox, I need linewords[2].
I was wondering how can we get the 'i' of a token in that linewords[i], because I want the output to be linewords[i-1]

Answer Source

That can be done by traversing the array and when you get your word , print the one before it.Here's how:-

return;//no preceding word

   for(int i=1;i<lineWords.length;i++){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download