从Java中的字符串中的两行之间读取 [英] Read between two lines from a String in Java

查看:70
本文介绍了从Java中的字符串中的两行之间读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一行文本行,我必须从该字符串中读取一个范围.

I have a stream of text lines and I have to read a range from this string.

例如,给定的字符串:

str = "1 ddsfsdfs
d
6 s4. 3t
sdfdsfsfsf
dfdsfsfdfsdfd
345345
dsfsdf45v";

而且我必须阅读范围之间的内容,即从第4行到第6行.

And I have to read between ranges i.e. from line 4 to line 6.

该怎么做?

好像我可以使用Java 8文本流.

Looks like I can use java 8 stream of text.

str.lines().collect(...)

但API不太熟悉.任何有钱人欢迎

But not quite gettign the API. Any pounters welcome

推荐答案

Lines API was added in Java 11. If you are running Java 11, then for the input String:

var str = "1 ddsfsdfs\n" +
            "    d\n" +
            "    6 s4. 3t\n" +
            "            sdfdsfsfsf\n" +
            "    dfdsfsfdfsdfd\n" +
            "    345345\n" +
            "    dsfsdf45v";

您可以执行以下操作:

String line4To6 = str.lines().skip(4).limit(6 - 4).collect(Collectors.joining(","));

哪个将产生以下输出:

dfdsfsfdfsdfd,    345345

从字符串中读取特定行的公式基本上是:

Basically, the formulae to read specific lines from the string is:

str.lines().skip(fromLineNumber).limit(toLineNumber - fromLineNumber).collect(Collectors.joining(","));

将从指定索引中读取行,但不包括起始索引中的行.

Which will read lines from the given index excluding line at starting index.

如果您正在运行低于11但高于8的任何Java版本,则可以通过将输入字符串拆分为新的字符串来创建 String Stream 来实现相同的目的线字符是这样的:

If you are running any Java version below 11 but above 8, the same thing can be achieved by creating a Stream of String by splitting the input string by a new line character something like this:

String line4To6 = Arrays.stream(str.split("\\n")).skip(4).limit(6 - 4).collect(Collectors.joining(","));

这篇关于从Java中的字符串中的两行之间读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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