Confusing output from String.split

前端 未结 8 1025
情深已故
情深已故 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

    String blank = "";                    
    String comma = ",";                   
    System.out.println("Output1: "+blank.split(",").length);  // case 1
    System.out.println("Output2: "+comma.split(",").length);  // case 2
    

    case 1 - Here blank.split(",") will return "" since there is no , in blank you get the same, So length will be 1

    case 2- Here comma.split(",") will return empty array, you have to scape , if you want to count comma with length 1 else length will be 0

    Again comma.split(",") split() expecting a regex as argument it will return result array to matching with that regex.

    The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string.

    Else

    If the expression does not match any part of the input then the resulting array has just one element, namely this string.

提交回复
热议问题