String split not returning empty results

前端 未结 9 1479
走了就别回头了
走了就别回头了 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:53

    This works,

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.File;
    import java.io.IOException;
    
    public class split {
    public static void main(String[] args)
    {
        String data = null;
        try {
        BufferedReader br = new BufferedReader(new FileReader(new File("split.csv")));
        while( (data=br.readLine())!=null)
        {
            System.out.println("line:"+data);
            String[] cols = data.split(":",-1);
            System.out.println("count:"+cols.length);
            for(int x=0;x<cols.length;++x)
            {
                System.out.println("["+x+"] =("+cols[x]+")");
            }
        }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    }
    

    Here is a test file,

    a:b:c:d:e
    a:b:c:d:
    a:b:c::
    a:b::: 
    a::::
    ::::
    ::::e
    :::d:e
    ::c:d:e
    :b:c:d:e
    a:b:c:d:e
    
    0 讨论(0)
  • 2020-12-02 01:00

    I don't honestly see the big draw of split. StringTokenizer works just as well for most things like this and will easily send back the tokens (so you can tell there was nothing in between :: ).

    I just wish it worked a little better with the enhanced for loop, but that aside, it wouldn't hurt to give it a try.

    I think there is a regexp trick to get your matched tokens to return as well but I've gone 20 years without learning regexp and it's still never been the best answer to any problem I've tackled (Not that I would actually know since I don't ever use it, but the non-regexp solutions are generally too easy to beat.)

    0 讨论(0)
  • 2020-12-02 01:02

    Using Guava's Splitter class:

    Iterable<String> split = Splitter.on(':').split("value1:value2::value3");
    

    Splitter does not omit empty results by default, though you can make one that does. Though it seems from what others are saying that what you're doing should work as well.

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