Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read second line from a string in java

Tags:

java

parsing

line

I have a string with multiple lines and I want to read a specific line and save it to an other string. That's my code

String text ="example text line\n
example text line\n
example text line\n
example text line\n
example text line\n
example text line\n
example text line\n";

String textline1="";
String textline2="";

on the above strings textline1 and textline2 I want to save the specific line.

like image 414
Jessy Jameson Avatar asked Aug 28 '26 22:08

Jessy Jameson


1 Answers

You can split on the new-line character:

//To split on the new line

String[] lines = s.split("\\n");

//To read 1st line

String line1 = lines[0];
System.out.println(line1);

//To read 2nd line

String line2 = lines[1];
System.out.println(line2);
like image 147
Bozho Avatar answered Aug 31 '26 16:08

Bozho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!