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!

You probably don't want charAt().

If you want to extend yourself, think about doing a regular expression that matches three words, the middle one "hello" and with sub-matches for the word before and the word after. That would be maybe three lines (for that part). Start here: http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/package-summary.html ... and in the pattern link, look for 'capturing group'.

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);


Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.