Hey all, I need help with this.
I have a .txt file, called "littlefile.txt", inside that .txt there is text of course and my java program is supposed to read that text (as a String), and find a word like ... "hello", ... that's ok, but the java program must print on screen the word that is before "hello" and the one that is after... and THAT'S what i need help with.

I think it could be done mixing methods like indexOf(); charAt();

Any help appreciated!

An easy method would be tokenize the whole String using the StringTokenizer available in java.util... your job will be much simpler.

Yeah, I thought about StringTokenizer, and I'm quite new to Java, but the thing is StringTokenizer only allows me to separate words, i dont know (or understand) how to "select" the next or last word T_T

it should be something like

if(nextword=hello){DO NOT PRINT hello, print this word im at!}
and if(hello has another word after it, print that word!)else(DONT!)

thats like a "draw" of my idea

One way is to have the variables 'prior' and 'current'. Initialize them to empty string, then as you iterate the tokens, copy the 'current' value into prior then the iterator value into current. Until you have copied "hello". Then print the value in prior, and the value that is the next iterator value. This is brittle (I wouldn't do it this way in production code) because it doesn't allow for a change in spec to show, say, the N prior and M subsequent values.

You also need to think about what happens if "hello" is the first or last word in the text.

OK! Solved it my way!

// NEXT WORD //z3 is linea.length(); //z8 is hello position; //Yeah, I speak Spanish;
String psiguiente = " "; char espacio = ' ';
for(int h5=z8+5;h5<=z3-1;h5++){
psiguiente = psiguiente + linea.charAt(h5); if((linea.charAt(h5))==(' ')) break; 
} System.out.print("\n  THE NEXT WORD IS: " + psiguiente);  

// The word before 'hello';
String panterior = " ";
for(int g=z8-2;g>=0;g--){
panterior = panterior + linea.charAt(g); if((linea.charAt(g)==(espacio))) break; 


} 
String panteriorInvertida = " "; 				//
for(int f=panterior.length()-1;f>=0;f--)
		panteriorInvertida = panteriorInvertida + panterior.charAt(f);
System.out.println("\n THE WORD BEFORE 'HELLO' IS: " + panteriorInvertida);

AND THATS HOW I DID IT - THANKS

Edited 6 Years Ago by z3r0acidk: n/a

This question has already been answered. Start a new discussion instead.