Reputation: 862
I have de next code:
String test = "A,B,,,,,";
String[] result = test.split(",");
for(String s : result){
System.out.println("$"+s+"$");
}
The output is:
$A$
$B$
and y I expected:
$A$
$B$
$$
$$
$$
$$
$$
but, I modified the code as follows:
String test = "A,B,,,,,C";
String[] result = test.split(",");
for(String s : result){
System.out.println("$"+s+"$");
}
and the result is:
$A$
$B$
$$
$$
$$
$$
$C$
other variation:
String test = "A,B,,,C,,";
String[] result = test.split(",");
for(String s : result){
System.out.println("$"+s+"$");
}
the result:
$A$
$B$
$$
$$
$C$
any idea?
I need this for convert csv file to java objects, but when they don't send me the last column the code not work correctly
Upvotes: 3
Views: 449
Reputation: 862
I have the solution thanks to @ZouZou, is the next:
String test = "A,B,,,C,,";
String[] result = test.split(",",test.length()); // or the number of elements you expect in the result
for(String s : result){
System.out.println("$"+s+"$");
}
Upvotes: 0
Reputation: 29
i did this code right now, it worked fine for me, try this:
String test = "A,B,,,,,";
int i;
int countOfCommas = 0;
int countOfLetters = 0;
String[] testArray = test.split("");
String[] result = test.split(",");
for(i=0;i<=test.length();i++)
if(testArray[i].equals(","))
countOfCommas++;
for(String s : result){
System.out.println("$"+s+"$");
}
if(test.length() > result.length)
countOfLetters = test.length()-countOfCommas;
for(i=0;i<(test.length()-countOfLetters)-result.length;i++)
System.out.println("$$");
Upvotes: 1
Reputation: 11911
As Jeroen Vannevel stated this is documented behaviour of String.split()
. If you need to kepp all empty Strings just use test.split(",",-1)
Upvotes: 0
Reputation: 44439
From the docs:
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
Upvotes: 2