ant
ant

Reputation: 22948

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?

Upvotes: 2

Views: 3674

Answers (3)

polygenelubricants
polygenelubricants

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.

See also

Upvotes: 3

Phani Kumar PV
Phani Kumar PV

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

Michael Mrozek
Michael Mrozek

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

Related Questions