How to prevent java.lang.String.split() from creating a leading empty string?

后端 未结 9 1341
天命终不由人
天命终不由人 2020-11-27 05:50

passing 0 as a limit argument prevents trailing empty strings, but how does one prevent leading empty strings?

for instance

String[] test =          


        
9条回答
  •  春和景丽
    2020-11-27 06:18

    I don't think there is a way you could do this with the built-in split method. So you have two options:

    1) Make your own split

    2) Iterate through the array after calling split and remove empty elements

    If you make your own split you can just combine these two options

    public List split(String inString)
    {
       List outList = new ArrayList<>();
       String[]     test    = inString.split("/");
    
       for(String s : test)
       {
           if(s != null && s.length() > 0)
               outList.add(s);
       }
    
       return outList;
    }
    

    or you could just check for the delimiter being in the first position before you call split and ignore the first character if it does:

    String   delimiter       = "/";
    String   delimitedString = "/Test/Stuff";
    String[] test;
    
    if(delimitedString.startsWith(delimiter)){
        //start at the 1st character not the 0th
        test = delimitedString.substring(1).split(delimiter); 
    }
    else
        test = delimitedString.split(delimiter);
    

提交回复
热议问题