Reading string more efficiently
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?
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"
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.
See also
- Scanner method to get a char
- How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
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];
}
精彩评论