1

When I split a string with multiple commas at end, they are ignored in array. Is it correct ?

    String a = "a,b,c,,f,,";
    String[] sdf = a.split(",");
    for (int i = 0; i < sdf.length; i++) {
        System.out.println(sdf[i]);
    }

Or am I missing something.

Output I am getting is

[a,b,c, ,f]   

I want to take those blank values into consideration, expecting something like this

[a,b,c, ,f, ,] 
Ninad Pingale
  • 6,801
  • 5
  • 32
  • 55

2 Answers2

4

You need to use:

public String[] split(String regex,
                  int limit)

and say:

String[] sdf = a.split(",", -1);

For your input, it'd produce:

[a, b, c, , f, , ]

Quoting from the documentation:

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

devnull
  • 118,548
  • 33
  • 236
  • 227
0

Yes, that's the way it's supposed to work.

See the answers to this question for more details, including how to bypass that behavior.

(tl;dr: use a.split(",", -1) to include the empty elements.)

Community
  • 1
  • 1
BambooleanLogic
  • 7,530
  • 3
  • 30
  • 56