Adding comma separated strings to an ArrayList and vice versa

前端 未结 11 1221
旧巷少年郎
旧巷少年郎 2021-01-01 05:18

How to add a comma separated string to an ArrayList? My string \"returnedItems\" could hold 1 or 20 items which I\'d like to add to my ArrayList \"selItemArrayList\".

<
相关标签:
11条回答
  • 2021-01-01 06:00
    import com.google.common.base.*;
    
    Iterable<String> items = Splitter.on(",").omitEmptyStrings()
                                     .split("Mango,Apple,Guava");
    
    // Join again!
    String itemsString = Joiner.join(",").join(items);
    
    0 讨论(0)
  • 2021-01-01 06:03
    String returnedItems = "a,b,c";
    List<String> sellItems = Arrays.asList(returnedItems.split(","));
    

    Now iterate over the list and append each item to a StringBuilder:

    StringBuilder sb = new StringBuilder();
    for(String item: sellItems){
        if(sb.length() > 0){
            sb.append(',');
        }
        sb.append(item);
    }
    String result = sb.toString();
    
    0 讨论(0)
  • 2021-01-01 06:07

    One-liners are always popular:

    Collections.addAll(arrayList, input.split(","));
    
    0 讨论(0)
  • 2021-01-01 06:08

    If the individual items aren't quoted then:

     QString str = "a,,b,c";
    
     QStringList list1 = str.split(",");
     // list1: [ "a", "", "b", "c" ]
    

    If the items are quoted I'd add "[]" characters and use a JSON parser.

    0 讨论(0)
  • 2021-01-01 06:08

    You could use the split() method on String to convert the String to an array that you could loop through.

    Although you might be able to skip the looping and parsing with a regular expression to remove the spaces using replaceAll() on a String.

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