3

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

3
  • omg you found a wierd bug :S Commented Nov 28, 2013 at 14:49
  • 3
    You can try String[] result = test.split(",",test.length());, and you'll see that you get your expected results. Commented Nov 28, 2013 at 14:51
  • 1
    Yes!!!! you're absolutely right! Commented Nov 28, 2013 at 14:54

4 Answers 4

2

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.

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

2 Comments

yes, but, if the empty string are not included, the result with the entry String test = "A,B,,,C,,"; should be {A,B,C} ?
@victorpacheco3107 No. Read the docs more carefully, it says "trailing empty strings". Not "empty strings anywhere".
1

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("$$");

Comments

0

As Jeroen Vannevel stated this is documented behaviour of String.split(). If you need to kepp all empty Strings just use test.split(",",-1)

Comments

0

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+"$");
}

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.