Join a string using delimiters

后端 未结 24 1658
北海茫月
北海茫月 2020-12-05 09:57

What is the best way to join a list of strings into a combined delimited string. I\'m mainly concerned about when to stop adding the delimiter. I\'ll use C# for my example

24条回答
  •  醉话见心
    2020-12-05 10:54

    In Java 8 we can use:

    List list = Arrays.asList(new String[] { "a", "b", "c" });
    System.out.println(String.join(",", list)); //Output: a,b,c
    

    To have a prefix and suffix we can do

    StringJoiner joiner = new StringJoiner(",", "{", "}");
    list.forEach(x -> joiner.add(x));
    System.out.println(joiner.toString()); //Output: {a,b,c}
    

    Prior to Java 8 you can do like Jon's answer

    StringBuilder sb = new StringBuilder(prefix);
    boolean and = false;
    for (E e : iterable) {        
        if (and) {
            sb.append(delimiter);
        }
        sb.append(e);
        and = true;
    }
    sb.append(suffix);
    

提交回复
热议问题