1

I have a string of around a hundred lines, it is unknown whether the lines will be "\r\n" or "\n".

I want to parse the string once, processing each line.

This question almost answers mine, but there's no mention of how to deal with unknown new line delimiting characters.

I was thinking of using one of the above methods, choosing "\n" as the delimiter and then stripping any "\r" characters on a line-by-line basis.

While performance really isn't an issue, I'd like to know if there is a cleaner way of doing this. I have not been able to find any methods that automatically handle line delimiter types.

Attempt #1, as per suggestion from @TritonMan:

Scanner scanner = new Scanner(myString);
String line = scanner.nextLine();
// line contains whole contents of string, not just the first line

If it matters, I am running this on Android. The string comes from a PLS file (playlist) which doesn't seem to be well defined anywhere, so I do not know what type of line delimiters it uses.

As a fallback, I will use the code from this question, but it's now bugging me how to do it without regex or String.split() in case I deal with streams:

String lines[] = String.split("\\r?\\n");
Community
  • 1
  • 1
CL22
  • 13,696
  • 23
  • 83
  • 147
  • 3
    Does the second answer not work for you? It should. The one that uses Scanner – Rocky Pulley Jul 29 '14 at 16:02
  • Ah great, thank you. I will try it – CL22 Jul 29 '14 at 16:04
  • It didn't work - please see my edit – CL22 Jul 30 '14 at 11:04
  • 1
    Scanner and BufferedReader don't care about the type of line ending. They will match both of them. [See also this answer](http://stackoverflow.com/questions/9259411/what-is-the-best-way-to-iterate-over-the-lines-of-a-java-string/9259462#9259462) – Guillaume Polet Jul 30 '14 at 12:47
  • Thanks - turns out (as you probably knew) I did not notice that other code stripped out the lines before passing it to mine. – CL22 Jul 30 '14 at 15:04

1 Answers1

1

Hint : JDK is open source! You can look how the Scanner class is implemented.

In short:

Scanner in = new Scanner(source);

while(in.hasNextLine())
    String line = in.nextLine();

    //Do something!

will store a line on both "\r\n" and "\n" cases.

qbit
  • 2,528
  • 2
  • 12
  • 27