2

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?

ant
  • 22,634
  • 36
  • 132
  • 182
  • couldn't you just substring the first line? before calling the method? – Yaneeve Apr 12 '10 at 15:30
  • A word of caution on substring. It will actually be backed by the original string unless you call intern. So if you use substring you should .intern() the result if you want the original string to be eligible for garbage collection. – M. Jessup Apr 12 '10 at 15:40
  • @M. Jessup Can you please post an answer how to do it? thank you – ant Apr 12 '10 at 15:41

3 Answers3

6

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"
Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
  • @Michael Mrozek Can I get an example? – ant Apr 12 '10 at 15:30
  • To be compatible with the different flavors of line breaks, you can't just chop at the first index of `\n`, because (i) you may get a leftover `\r`, or (ii) you may never even see `\n` if the line break is `\r`. – polygenelubricants Apr 14 '10 at 01:47
3

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

Community
  • 1
  • 1
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
  • 1
    +1 for the more "concise and readable option". While `str.substring(0, str.indexOf("\n"))` is efficient, it's not immediately obvious to me that it returns a line. – Iain Samuel McLean Elder Apr 14 '10 at 01:09
0
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];
        }
Phani Kumar PV
  • 906
  • 11
  • 22
  • 5
    He said the input string is pretty big; there's really no need to walk the entire thing splitting on each newline if he only needs the first one – Michael Mrozek Apr 12 '10 at 15:35