我怎样才能让我的程序对于字符串中读取的每个单词也读取下面的单词?

发布于 2025-01-18 00:44:35 字数 412 浏览 2 评论 0原文

我希望我的Java程序做以下操作: 每当它读取以下文件

Bob went to the store to buy apples.

以读取字符串中的每个单词(仅由单个空格字符界定)并读取下一个单词,但也没有“移动”主阅读器时。因此,它将做类似的事情:

for word in string{
     print word + nextWord;
}

其输出将进行

Bob went
went to
to the
the store
store to
to buy
buy apples.

编辑:重要!我不想读取整个文件并将其加载到内存中。我希望此操作直接在文件上进行。想象一下,我正在处理巨大的东西,例如整本书或更多。

I want my Java program to do the following thing:
Whenever it reads a file like the following

Bob went to the store to buy apples.

To read each word in the string (delimited by only a single space character) and to also read the next word, but without "moving" the main reader as well. So it would do something like this:

for word in string{
     print word + nextWord;
}

And its output would be

Bob went
went to
to the
the store
store to
to buy
buy apples.

Edit: IMPORTANT! I don't want to read the whole file and load it into memory. I want this operation to happen DIRECTLY on the file. Imagine I am dealing with something huge, like a whole book, or more.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏日浅笑〃 2025-01-25 00:44:35

不可以。扫描仪不允许您查看未来的输入。

然而,编写代码很简单:

Scanner s = new Scanner(new FileInputStream("myfile.txt");
String previous = s.next();
while (s.hasNext()) {
    String next = s.next();
    System.out.println(previous + " " + next);
    previous = next;
}

No. Scanner doesn't let you peek at future input.

However, it's trivial to code:

Scanner s = new Scanner(new FileInputStream("myfile.txt");
String previous = s.next();
while (s.hasNext()) {
    String next = s.next();
    System.out.println(previous + " " + next);
    previous = next;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文