Java String split is not working

后端 未结 3 1700
悲&欢浪女
悲&欢浪女 2021-01-22 19:27

Java Experts ,

Please look into the below split command code and let me know why last two nulls are not captured.

String test = \"1,O1,,,,0.0000,0.0000,         


        
相关标签:
3条回答
  • 2021-01-22 19:43

    split silently discards trailing separators, as specified in the Javadoc.

    In general, the behavior of split is kind of weird. Consider using Guava's Splitter instead, which has somewhat more predictable and customizable behavior. (Disclosure: I contribute to Guava.)

    Splitter.on(',').split("1,O1,,,,0.0000,0.0000,,");
    // returns [1, O1, , , , 0.0000, 0.0000, , ]
    Splitter.on(',').omitEmptyStrings()
      .split("1,O1,,,,0.0000,0.0000,,");
    // returns [1, O1, 0.0000, 0.0000]
    
    0 讨论(0)
  • 2021-01-22 19:43

    As mentioned above, test.split(","); will ignore trailing blank strings. You could use the two parameter method with a large second argument. However, the API also states

    If n is non-positive then the pattern will be applied as many times
    as possible and the array can have any length.
    

    where n is the second argument. So if you want all the trailing strings, I would recommend

    test.split(",", -1);

    0 讨论(0)
  • 2021-01-22 19:56

    It behaves as specified in the javadoc:

    This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

    If you want to keep the trailing blank strings, you can use the 2 argument split method with a negative limit:

    String[] splittest = test.split(",", -1);
    

    If the limit is non-positive then the pattern will be applied as many times as possible and the array can have any length.

    0 讨论(0)
提交回复
热议问题