7
String abc = "a,b,c,d,,,";
String[] arr = abc.split(",");
System.out.println(arr.length);

Output is 4. But obviously my expectation is 7. Here is my solution:

String abc = "a,b,c,d,,,";
abc += "\n";
String[] arr = abc.split(",");
System.out.println(arr.length);

Why does it happen? Anyone could give my a better solution?

1
  • 1
    correct.. use str.split(",", -1); an overloaded method Commented Apr 15, 2014 at 10:10

5 Answers 5

9

Use the alternative version of String#split() that takes two arguments to achieve this:

String abc = "a,b,c,d,,,";
String[] arr = abc.split(",", -1);
System.out.println(arr.length);

This prints

7

From the Javadoc linked above:

If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

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

1 Comment

+1 for using the overloaded split() rather than regex.
4

You can use lookahead:

String abc = "a,b,c,d,,,";
String[] arr = abc.split("(?=,)");
System.out.println(arr.length); //7

8 Comments

This is not the case here, although it works, it complicates the case with regex - specific operator
What do you mean by that comment and how can simple lookahead becomes complicated?
Answer is as simple as reading javadoc and adding parameter to split call, You don't need to refer to regex cookbook to get this done.
You seem to be day dreaming. Who referred a regex cookbook here? For unknowns there is no split without regex support in Java.
You know that, I know that, most of Jdevs know that (at least I hope most do)...but not everyone, and using this solution requires to know not only most basic regex rules but also groups and lookahead operator
|
1

Use:

String[] arr = abc.split("(?=,)");

to split abc

1 Comment

This is not the case here, although it works, it complicates the case with regex - specific operator
1

This is because split does not include only trailing empty strings, but if you have \n at the end, then the last element is not empty

[a, b, c, d, , , \n]

Comments

0

split() is coded to that very job. You can count a character or string occurrence in the below way.

        String ch = ",";
    int count = 0;
    int pos = 0;
    int idx;
    while ((idx = abc.indexOf(ch, pos)) != -1) {
        ++count;
        pos = idx + sub.length();
    }
    System.out.println(count);

This very logic is used in Spring.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.