Java - Split and trim in one shot

后端 未结 8 933
鱼传尺愫
鱼传尺愫 2020-12-13 23:25

I have a String like this : String attributes = \" foo boo, faa baa, fii bii,\" I want to get a result like this :

String[] result = {\"foo boo\         


        
相关标签:
8条回答
  • 2020-12-14 00:11

    Use regular expression \s*,\s* for splitting.

    String result[] = attributes.split("\\s*,\\s*");
    

    For Initial and Trailing Whitespaces
    The previous solution still leaves initial and trailing white-spaces. So if we're expecting any of them, then we can use the following solution to remove the same:

    String result[] = attributes.trim().split("\\s*,\\s*");
    
    0 讨论(0)
  • 2020-12-14 00:13
    // given input
    String attributes = " foo boo, faa baa, fii bii,";
    
    // desired output
    String[] result = {"foo boo", "faa baa", "fii bii"};
    

    This should work:

    String[] s = attributes.trim().split("[,]");
    

    As answered by @Raman Sahasi:

    before you split your string, you can trim the trailing and leading spaces. I've used the delimiter , as it was your only delimiter in your string

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