[CSC 204] Reading Words from a Text File
Andrew J. Pounds
pounds_aj at mercer.edu
Thu Apr 16 09:08:02 EDT 2009
Several of you have asked me for help with reading words from a text
file. Assuming that you have "in" tied to an input file, the following
should read "words" and print them out to the screen. The basic idea is
that you read in a string, strip off everything to the first space and
call that a word. You then move the index to the next word in the
string and keep repeating the procedure until you get to the end of the
line.
You may have to do some further cleanup -- but I think you can handle that.
while (in.hasNextLine()) {
String line = in.nextLine().trim();
index = line.indexOf(" ");
while ( index != -1 ) { // This assures we are not at the last word
String word = line.substring(0,line.indexOf(" ")); // Strip off the word
System.out.println(word);
// Now make the line to be searched smaller
line = line.substring(line.indexOf(" ")+1,line.length()).trim();
index = line.indexOf(" ");
}
// At this point we have reached the last word in the line
String word = line.substring(0,line.length());
System.out.println(word);
index = 0;
}
--
Andrew J. Pounds, Ph.D. (pounds at theochem.mercer.edu)
Associate Professor of Chemistry and Computer Science
Mercer University, Macon, GA 31207 (478) 301-5627
More information about the csc204
mailing list