1

What is the equivalent for this C# code in Java?

string receivedData = …;
string splittedValues = receivedData.Split("&", StringSplitOptions.RemoveEmptyEntries);

3 Answers 3

6

final String[] splittedValues = receivedData.replaceFirst("^&+","").split("&+");

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

3 Comments

Failed for "&&sdfds". An empty string is in the result.
@nhahtdh You don't even need two && to get that.
@Joey: You sure you tested? Even without the trimming, it works correctly.
0

With Guava:

Iterable<String> splitStrings = 
  Splitter.on('&').omitEmptyStrings().split(string);

(Disclosure: I contribute to Guava.)

Comments

0

For the particular code above, you can first:

  • Remove leading/trailing tokens of the delimiter: .replaceAll("(^&+|&+$)", "")
  • Split the string according to the delimiter: .split("&+")

Without the first step clean up, empty string will be in the result of splitting the string "&&sdfds" (leading delimiter).

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.