1

in C# I can use the StringSplitOption.None enum element to specify that I want empty strings to be included in the resulting array:

String[] s = text.Split(new String[] { "\r\n" }, StringSplitOptions.None);

In java I can do the following:

 String[] s= text.split("\r\n");

However, the split method does not return empty strings. (So if text = "a\r\nb\r\n", I want to get {a, b, ""}, rather than {a, b}).

Is there an easy way to accomplish this either via a regex or using some other method?

2 Answers 2

4

You could use -1 as your String#split limit:

System.out.println(Arrays.toString("a\r\nb\r\n".split("\\r\\n", -1)));
Sign up to request clarification or add additional context in comments.

Comments

1

Use Guava's Splitter. Generally much more logical in terms of how it works.

import com.google.common.base.Splitter;
...
System.err.println(Splitter.on("\r\n").split("a\r\nb\r\n"));    

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.