Reading a string is more efficient
You can use indexOf()
to find the first line break, and substring()
to take a substring from 0 to that line break
Edit: Example (assuming line break is \ n):
String str = "Line 1\nLine 2\nLine 3";
String firstLine = str.substring(0, str.indexOf("\n"));
//firstLine == "Line 1"
source to share
The most concise and readable option is to use java.util.Scanner
.
String reallyLongString = //...
String firstLine = new Scanner(reallyLongString).nextLine();
Scanner
- a much more advanced alternative to the outdated one StringTokenizer
; it can analyze int
, double
, boolean
, BigDecimal
, regular expression patterns, etc. of anything Readable
, with congestion designer, who also take File
, InputStream
, String
etc ..
see also
source to share