How to read spaces with a .next () scanner

I have a scanner and set the delimiter to "", but it still won’t read spaces with the following method (). I know that nextline () works, but I need to examine each character in the input individually, including spaces; this is for the complex task of data analysis. I'm at a dead end. Google did not find anything.

Can anyone help me with this? I think about turning a space into a special character, and then to analyze the character, put it back in the space contained in the line ... It looks like it's too complicated! Is there a more elegant way to do this?

EDIT: My main task is to take a string and list it by character several times to examine the data for various tasks. You will have to examine it many times, one character at a time, and so I thought that the scanner class would be my best choice, since it can be easily worked with (at least for me). This is my task. Is there an easier way to do this?

+3
source share
4 answers
Scanner scanner = new Scanner(file).useDelimiter("'") 

But it is very inefficient. The best way forward: reading character by character:

 private static void readCharacters(Reader reader) throws IOException { int r; while ((r = reader.read()) != -1) { char ch = (char) r; doSomethingWithChar(ch); } } 

Also see HERE

+4
source

instead

 scanner.next(); 

using

 scanner.nextLine(); 

This way you solve the problem with delimiters.

+1
source

Use a BufferedReader to read an input line, and then iterate over the line in a for loop, working with each char .
You can check if the character is a space on Character.isWhitespace(char c) .

0
source

Try .useDelimiter("(\\b|\\B)")

It will use the borders of each character as a separator.

The following code will print exactly what the user has typed. No character will be ignored, including spaces.

 Scanner charScanner = new Scanner( System.in ).useDelimiter( "(\\b|\\B)" ) ; while( charScanner.hasNext() ) System.out.print( charScanner.next() ) ; 
0
source

All Articles