Confusing output from String.split

前端 未结 8 1038
情深已故
情深已故 2020-12-08 06:33

I do not understand the output of this code:

public class StringDemo{              
    public static void main(String args[]) {
        String blank = \"\";         


        
8条回答
  •  渐次进展
    2020-12-08 06:47

    The API for the split method states that "If the expression does not match any part of the input then the resulting array has just one element, namely this string."

    So, as the String blank doesn't contain a ",", a String[] with one element (i.e. blank itself) is returned.

    For the String comma, "nothing" is left of the original string thus an empty array is returned.

    This seems to be the best solution if you want to process the returned result, e. g.

    String[] splits = aString.split(",");
    for(String split: splits) {
       // do something
    }
    

提交回复
热议问题