2

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
mastermind
  • 161
  • 1
  • 2
  • 8
  • 1
    You can't have a String like the one in your example because Java won't let you split strings over multiple lines without concatenation. – BunjiquoBianco Sep 07 '12 at 15:10

3 Answers3

2

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];
Daniel André
  • 1,158
  • 1
  • 12
  • 28
1

Split your input string depending on its formatting..

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

See documentation for split() method here.

Michal Klouda
  • 14,263
  • 7
  • 53
  • 77
1
String[] strings = str.split('\\n');
if (strings.length > 1){
  return strings[1];
}
kosa
  • 65,990
  • 13
  • 130
  • 167
srini.venigalla
  • 5,137
  • 1
  • 18
  • 29