如何使用scanner.next()读取空白 [英] How to read whitespace with scanner.next()

查看:438
本文介绍了如何使用scanner.next()读取空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个扫描仪,并且已将定界符设置为",但是它仍然不会使用next()方法读取空格.我知道nextline()可以工作,但是我需要单独检查输入中的每个字符,包括空格;这是一个复杂的数据分析问题.不过,我很困惑.谷歌什么也没发现.

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?

我的主要任务是,获取一个String,并逐个字符遍历该字符串,以检查各种任务的数据.您将不得不多次检查它,一次检查一个字符,因此我认为最好使用扫描仪类,因为它很容易使用(至少对我而言).那是我的任务有没有更简单的方法可以解决这个问题?

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?

推荐答案

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

另请参见此处

这篇关于如何使用scanner.next()读取空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆