daddylonglegs
daddylonglegs

Reputation: 85

How can I implement a string split method in Java like c# does

In C#, if I have a string like this:

String test = ";;;;";
String[] split = test.Split(';');
Console.WriteLine(split.Length); // Then I got 5 here

But in Java:

String test = ";;;;";
String[] split = test.split(";");
System.out.println(split.length); // Then I got only 1 here

Upvotes: 2

Views: 2349

Answers (2)

fge
fge

Reputation: 121830

Use:

test.split(";", -1);

This is an unfortunate design decision; by default, .split() will trim (most) empty strings from the end of the result array.

If you want a real splitter, use Guava's Splitter. It performs much better than the JDK's .split() method, is unassuming and doesn't have to use a regex as an argument!

Upvotes: 6

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285430

Try:

  String test = ";;;;";
  String[] split = test.split(";", -1);
  System.out.println(split.length);

The String API explains this method overload that also adds a limit field.

If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.

Upvotes: 9

Related Questions