String split not returning empty results

前端 未结 9 1478
走了就别回头了
走了就别回头了 2020-12-02 00:12

I\'m trying to use

\"value1:value2::value3\".split(\":\");

Problem is that I want it to include the blank results.

It returns:

相关标签:
9条回答
  • 2020-12-02 00:41
    public static void main(String[] args){
      String[] arr = "value1:value2::value3".split(":");
      for(String elm:arr){
        System.out.println("'"+elm+"',");
      }
      System.out.println(arr.length);
    }
    

    prints

    'value1',
    'value2',
    '',
    'value3',
    4
    

    Which is exactly what you want. Your mistake is somewhere else...

    0 讨论(0)
  • 2020-12-02 00:42

    split does include empty matches in the result, have a look at the docs here. However, by default, trailing empty strings (those at the end of the array) are discarded. If you want to include these as well, try split(":", -1).

    0 讨论(0)
  • 2020-12-02 00:42

    I think that a StringTokenizer might work better for you, YMMV.

    0 讨论(0)
  • 2020-12-02 00:42

    That should work but give StringTokenizer a go if you're still having issues.

    0 讨论(0)
  • 2020-12-02 00:43

    Use a negative limit in your split statement:

    String str = "val1:val2::val3";
    String[] st = str.split(":", -1);
    for (int i = 0; i< st.length; i++)
        System.out.println(st[i]);
    

    Results:

    val1
    val2
    
    val3
    
    0 讨论(0)
  • 2020-12-02 00:52

    Works for me.

    class t {
        public static void main(String[] _) {
            String t1 = "value1:value2::value3";
            String[] t2 = t1.split(":");
            System.out.println("t2 has "+t2.length+" elements");
            for (String tt : t2) System.out.println("\""+tt+"\"");
        }
    }
    

    gives the output

    $ java t
    t2 has 4 elements
    "value1"
    "value2"
    ""
    "value3"
    
    0 讨论(0)
提交回复
热议问题