Split strings keeping all trailing empty elements

后端 未结 3 1605
长发绾君心
长发绾君心 2021-01-25 07:28

I am relatively new to java programming. How would you split following lines of Strings separated by semicolons?

String; String; String; String, String; String;;         


        
相关标签:
3条回答
  • 2021-01-25 07:49

    The issue is the String.Split does not keep the trailing empty elements:

    Trailing empty strings are therefore not included in the resulting array.

    To include them, use -1 as the second argument (see demo):

    String s  = "String; String; String; String, String; String;;String;";
    System.out.println(Arrays.toString(s.split(";", -1)));
    

    See this Java reference:

    public String[] split(String regex, int limit)
    The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array... If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

    0 讨论(0)
  • 2021-01-25 07:56

    Since you stated that you want to contain the spaces, only split on the ; and want to keep 8 arguments for your constructor, we are going to use the split with a limit method.

    String.split(String,int)

    Example:

    String in = "String; String; String; String, String; String;;String;";
    String[] s1 = in.split(";");
    

    Gives:

    ["String"," String"," String, String"," String"," String","","String"]
    

    What is only 7 in length and will fail your constructor.


    String[] s = in.split(";",8);
    

    Gives:

    ["String"," String"," String"," String, String"," String","","String",""]`
    

    What is 8 in length and will work.


    You can then address your constructor using:

    YourObject obj = new YourObject(s[0],s[1],s[2],s[3],s[4],s[5],s[6],s[7]);
    
    0 讨论(0)
  • 2021-01-25 08:09

    Your answer is in the javadoc.

    String toto = "A;B;C;D";
    
    String[] tokens = toto.split(";");
    
    0 讨论(0)
提交回复
热议问题