Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substring by line number

Tags:

java

string

Is there a way to substring by the string line?

Someting like: String.substring(line_num);

Or we hava to do it manually by calculating the indexes?

like image 205
Michael A Avatar asked Jul 29 '26 02:07

Michael A


1 Answers

No, that's not possible. You can, however, split the string by \n and then get the required line:

String s = "First line\nSecond line\nThird line\nFourth line";
String[] lines = s.split("\n", -1);
System.out.println(lines[2]); // Third line

If you don't know what the line separator of your platform is, use System.getProperty("line.separator").

Or if you want to get a range of lines, use Arrays.copyOfRange():

String s = "First line\nSecond line\nThird line\nFourth line";
String[] lines = s.split("\n", -1);
String[] lines2To4 = Arrays.copyOfRange(lines, 1, 4);
like image 161
João Silva Avatar answered Jul 31 '26 17:07

João Silva