AlexC AlexC - 2 months ago 5
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(",");
System.out.println(tokens.length);


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)
-1
-2
-


and in C#:

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


What am I missing?

This is Java 1.8.0_101.

Answer

Use overloaded version of the method:

tokens = line.split(",", -1)
Comments