Java - Split and trim in one shot

后端 未结 8 932
鱼传尺愫
鱼传尺愫 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-13 23:48

    What about spliting with comma and space:

    String result[] = attributes.split(",\\s");
    
    0 讨论(0)
  • 2020-12-13 23:54

    Using java 8 you can do it like this in one line

    String[] result = Arrays.stream(attributes.split(",")).map(String::trim).toArray(String[]::new);
    
    0 讨论(0)
  • 2020-12-14 00:01

    If there is no text between the commas, the following expression will not create empty elements:

    String result[] = attributes.trim().split("\\s*,+\\s*,*\\s*");
    
    0 讨论(0)
  • 2020-12-14 00:01

    create your own custom function

    private static String[] split_and_trim_in_one_shot(String string){
     String[] result  = string.split(",");
     int array_length = result.length;
    
     for(int i =0; i < array_length ; i++){
      result[i]=result[i].trim();
     }
     return result;
    

    Overload with a consideration for custom delimiter

    private static String[] split_and_trim_in_one_shot(String string, String delimiter){
     String[] result  = string.split(delimiter);
     int array_length = result.length;
    
     for(int i =0; i < array_length ; i++){
      result[i]=result[i].trim();
     }
     return result;
    
    0 讨论(0)
  • 2020-12-14 00:09

    Best way is:

    value.split(",").map(function(x) {return x.trim()});
    
    0 讨论(0)
  • 2020-12-14 00:10
    String result[] = attributes.trim().split("\\s*,[,\\s]*");
    

    previously posted here: https://blog.oio.de/2012/08/23/split-comma-separated-strings-in-java/

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