0

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

As an example, a given string:

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

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

How to do it?

Looks like I can use java 8 stream of text.

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

But not quite gettign the API. Any pounters welcome

seenukarthi
  • 8,241
  • 10
  • 47
  • 68
Exploring
  • 2,493
  • 11
  • 56
  • 97
  • The java code in your question does not compile. Also, method [lines](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#lines()) was added in Java 11. – Abra Apr 21 '21 at 05:15
  • "not quite gettign the API" - well, I'd encourage you to grab a tutorial then and try to get familiar with it. Have a special look at the `skip()` and `limit()` methods. – Thomas Apr 21 '21 at 05:17
  • 1
    Please describe exactly what you mean by "read between ranges" and provide sample inputs and their expected outputs. – Bohemian Apr 21 '21 at 05:41
  • 1
    `result = str.replaceFirst("(.*\\R){4}((.*\\R){2})(?s).*", "$2");` – Holger Apr 21 '21 at 08:59

1 Answers1

3

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";

You can do something like this:

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

Which will produce an output of:

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.

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(","));
Shyam Baitmangalkar
  • 1,075
  • 12
  • 18