AlexC AlexC - 1 year ago 73
Java Question

Why does Java 8's split not produce the last token

I would expect the following Java code to split a string into three items:

String csv = "1,2,";
String[] tokens = csv.split(",");

However, I am only getting two items.

I must admit that I did not analyze this very deeply, but it seems counter-intuitive to me. Both Python and C# generate three items, as follows, in Python:

def test_split(self):
line = '1,2,'
tokens = line.split(",")
for token in tokens:
print('-' + token)

and in C#:

public void t()
string s = "1,2,";
var tokens = s.Split(',');
foreach (var token in tokens)
Console.WriteLine("-" + token);

What am I missing?

This is Java 1.8.0_101.

Answer Source

Use overloaded version of the method:

tokens = line.split(",", -1)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download