简体   繁体   中英

Display the second line of a string in java

Given a String like :

String str= "line1
line2
line3
line4";

How to display one specific line? For example the third one, like

System.out.println([...]str[...]);

which in terminal will display:

line3

You can use the split statement. It separates strings by a given regex. In this case the regex would be \\n:

String[] lines;

  String regex= "\\n";
  lines = str.split(regex);

you can then acces line 3 by using:

String line3 = lines[2];

Split your input string depending on its formatting..

System.out.println(str.split('\\n')[2]);

See documentation for split() method here .

String[] strings = str.split('\\n');
if (strings.length > 1){
  return strings[1];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM