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");
4
  • 3
    Does the second answer not work for you? It should. The one that uses Scanner Commented Jul 29, 2014 at 16:02
  • It didn't work - please see my edit Commented Jul 30, 2014 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 Commented Jul 30, 2014 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. Commented Jul 30, 2014 at 15:04

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.