Reading a string is more efficient

I am getting a rather large line of input into my method, but I really only need the first line of that line. Is it possible to retrieve only the first row of an already existing row?

+2


source to share


3 answers


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"

      

+6


source


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

+3


source


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];
        }

      

0


source







All Articles