Reputation: 22948
I'm getting pretty big input string into my method, but what I actually need is just first line of that string. Is it possible to extract just the first line of an already existing string?
Upvotes: 2
Views: 3674
Reputation: 383866
The most concise and readable option is to use java.util.Scanner
.
String reallyLongString = //...
String firstLine = new Scanner(reallyLongString).nextLine();
Scanner
is a much more advanced alternative for the legacy StringTokenizer
; it can parse int
, double
, boolean
, BigDecimal
, regex patterns, etc, from anything Readable
, with constructor overloads that also take a File
, InputStream
, String
, etc.
Upvotes: 3
Reputation: 892
public string FirstLine(string inputstring)
{
//split the given string using newline character
string[] strarray = inputstring.Split('\n');
//return the first element in the array as that is the first line
return strarray[0];
}
Upvotes: 0
Reputation: 175585
You can use indexOf()
to find the first line break, and substring()
to take the substring from 0 to that line break
Edit: Example (assuming the line break is \n):
String str = "Line 1\nLine 2\nLine 3";
String firstLine = str.substring(0, str.indexOf("\n"));
//firstLine == "Line 1"
Upvotes: 6