Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

java - How to read whitespace with scanner.next()

I have a scanner, and have set the delimiter to "", but it still won't read whitespaces with the next() method. I know that nextline() works, but I need to examine every character in the input individually, including whitespace; it's for a complex data analysis problem. I'm stumped, though. Google has turned up nothing.

Can anyone help me with this? I'm thinking of reversing the whitespace into a special character, then for the purposes of analyzing the character, reverse it back into a space, contained in a string... That seems way overkill though! Is there a more elegant way of doing this?

EDIT: My main task is, take a String, and go over it character-by-character, multiple 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 the scanner class would be my best bet since it can be easy to work with (for me at least). That's my task. Is there an easier way to go about this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Scanner scanner = new Scanner(file).useDelimiter("'")

But this is highly inefficient. The better way forward would be: to read 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...