0

Can somebody check the code below and explain the second case ?

public class SplitMain {

    public static void main(String[] args) {
        String[] arr = {"", "/", "as/d"};
        for (String s : arr){
            System.out.println(" Output : " + printStrArr(s.split("/")));   
        }
    }

    public static String printStrArr(String[] ar){
        String out = "";
        System.out.println("Length = " + ar.length);
        for (String s1 : ar){
            out += (s1 + "--");
        }       
        return out;
    }
}

Result ::

Length = 1 Output : --

Length = 0 Output :

Length = 2 Output : as--d--

When the input is just "", the output length is 1, which makes sense; the thirdcase is the normal case; but the second case, when input is "/", the result array is of length 0. Why is that ?

Morteza Asadi
  • 1,819
  • 2
  • 22
  • 39
sid_09
  • 461
  • 4
  • 18
  • 1
    When you `"/".split("/")` at first array with two empty strings is created `["", ""]`, but by default trailing empty strings are removed so this applies to all strings in this array, we are ending with empty array `[]`. But removing trailing empty strings makes sense only *if these empty string ware created as result of splitting*. So in your first case `"".split(anything)` result array will contain `[""]` and that empty string despite being trailing will not be removed because it wasn't created as result of splitting. – Pshemo Jan 21 '17 at 11:44
  • Thanks. Checked the split code in Pattern class. – sid_09 Jan 21 '17 at 12:11

1 Answers1

0

It's because of the way in which String.split() works - it essentially removes the delimiter on which it splits

The javadoc even contains this example:

The string "boo:and:foo", for example, yields the following results
with these expressions: 

Regex      Result

:  { "boo", "and", "foo" }} 
o  { "b", "", ":and:f" }}

So "/".split("/") returns an empty array.

Malt
  • 28,965
  • 9
  • 65
  • 105
  • 1
    The example is not the best one, it does not show anything. Simple copy paste from Oracle's doc. – Grzegorz Górkiewicz Jan 21 '17 at 11:27
  • It shows two examples of how `split` works, including the removal of the delimiter And yes, it's from the Javadoc as I've mentioned explicitly – Malt Jan 21 '17 at 11:40
  • Somehow it shows removal of the last delimiter, but you do not say that it removes all trailing delimiters. Anyway, I did not downvote your question ;) – Grzegorz Górkiewicz Jan 21 '17 at 11:42
  • "it essentially removes the delimiter on which it splits" while being true doesn't explain anything. For instance using this rule it is could also be possible to get from `"foo".split("o")` result array `["f","",""]` (delimiters are also removed here), but for some reason we are always getting `["f"]`. Your answer doesn't explain *why* this happens, it just states that it does which OP can observe from his own example. – Pshemo Jan 21 '17 at 12:07