Java StringTokenizer, empty null tokens

前端 未结 5 1600
有刺的猬
有刺的猬 2021-01-04 14:32

I am trying to split a string into 29 tokens..... stringtokenizer won\'t return null tokens. I tried string.split, but I believe I am doing something wrong:

         


        
5条回答
  •  无人及你
    2021-01-04 14:46

    If you want the trailing empty strings to be kept, but you don't want to give a magic number for maximum, use a negative limit:

    line.split(",", -1)
    

    If line.equals("a,,c"), then line.split(",", -1)[1].isEmpty(); it's not null. This is because when "," is the delimiter, then ",," has an empty string between the two delimiters, not null.


    Example:

    Using the explanation above, consider the following example: ",,"

    Although you might expect ",", null, and ",".

    The actual result is ",", "" and ","


    If you want null instead of empty strings in the array returned by split, then you'd have to manually scan the array and replace them with null. I'm not sure why s == null is better than s.isEmpty(), though.

    See also

    • Java String.indexOf and empty strings

提交回复
热议问题