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

后端 未结 9 1340
天命终不由人
天命终不由人 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:20

    Apache Commons has a utility method for exactly this: org.apache.commons.lang.StringUtils.split

    StringUtils.split()

    Actually in our company we now prefer using this method for splitting in all our projects.

    0 讨论(0)
  • 2020-11-27 06:27

    Your best bet is probably just to strip out any leading delimiter:

    String input = "/Test/Stuff";
    String[] test = input.replaceFirst("^/", "").split("/");
    

    You can make it more generic by putting it in a method:

    public String[] mySplit(final String input, final String delim)
    {
        return input.replaceFirst("^" + delim, "").split(delim);
    }
    
    String[] test = mySplit("/Test/Stuff", "/");
    
    0 讨论(0)
  • 2020-11-27 06:33

    You can use StringTokenizer for this purpose...

    String test1 = "/Test/Stuff";
            StringTokenizer st = new StringTokenizer(test1,"/");
            while(st.hasMoreTokens())
                System.out.println(st.nextToken());
    
    0 讨论(0)
提交回复
热议问题