I am trying to simply read words in a text file using scanner.next() with delimiter equal " " but the scanner includes the newline/carriage return with the token.
I have scoured the internet trying to find a good example of this problem and have not found it so I am posting it here. I can't find another similar problem posted here on SO. I also looked over the documentation on scanner and pattern (http://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html) but I still cannot find a way to solve this.
Text file:
This is a test
to see if1 this, is working
ok!
Code:
int i = 0;
String string;
try(Scanner scanner = new Scanner(new File(filename))) {
scanner.useDelimiter(" ");
while(scanner.hasNext())
{
string = scanner.next();
System.out.println(i++ + ": " + string);
}
}catch(IOException io_error) {
System.out.println(io_error);
}
Output:
0: This
1: is
2: a
3: test
to
4: see
5: if1
6: this,
7: is
8: working
ok!
As you can see, #3 and #8 have two words separated by a newline. (I know I can separate these into two separate strings.)