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(","));