Join a string using delimiters

后端 未结 24 1458
北海茫月
北海茫月 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<String> 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);
    
    0 讨论(0)
  • 2020-12-05 10:55

    For python be sure you have a list of strings, else ','.join(x) will fail. For a safe method using 2.5+

    delimiter = '","'
    delimiter.join(str(a) if a else '' for a in list_object)
    

    The "str(a) if a else ''" is good for None types otherwise str() ends up making then 'None' which isn't nice ;)

    0 讨论(0)
  • 2020-12-05 10:57

    This is a Working solution in C#, in Java, you can use similar for each on iterator.

            string result = string.Empty; 
    
            // use stringbuilder at some stage.
            foreach (string item in list)
                result += "," + item ;
    
            result = result.Substring(1);
            // output:  "item,item,item"
    

    If using .NET, you might want to use extension method so that you can do list.ToString(",") For details, check out Separator Delimited ToString for Array, List, Dictionary, Generic IEnumerable

    // contains extension methods, it must be a static class.
    public static class ExtensionMethod
    {
        // apply this extension to any generic IEnumerable object.
        public static string ToString<T>(this IEnumerable<T> source,
          string separator)
        {
            if (source == null)
               throw new ArgumentException("source can not be null.");
    
            if (string.IsNullOrEmpty(separator))
               throw new ArgumentException("separator can not be null or empty.");
    
            // A LINQ query to call ToString on each elements
            // and constructs a string array.
            string[] array =
             (from s in source
              select s.ToString()
              ).ToArray();
    
            // utilise builtin string.Join to concate elements with
            // customizable separator.
            return string.Join(separator, array);
        }
    }
    

    EDIT:For performance reasons, replace the concatenation code with string builder solution that mentioned within this thread.

    0 讨论(0)
  • 2020-12-05 10:59

    In C# you can just use String.Join(separator,string_list)

    0 讨论(0)
  • 2020-12-05 11:00

    I would express this recursively.

    • Check if the number of string arguments is 1. If it is, return it.
    • Otherwise recurse, but combine the first two arguments with the delimiter between them.

    Example in Common Lisp:

    (defun join (delimiter &rest strings)
      (if (null (rest strings))
          (first strings)
          (apply #'join
                 delimiter
                 (concatenate 'string
                              (first strings)
                              delimiter
                              (second strings))
                 (cddr strings))))
    

    The more idiomatic way is to use reduce, but this expands to almost exactly the same instructions as the above:

    (defun join (delimiter &rest strings)
      (reduce (lambda (a b)
                (concatenate 'string a delimiter b))
              strings))
    
    0 讨论(0)
  • 2020-12-05 11:02

    From http://dogsblog.softwarehouse.co.zw/post/2009/02/11/IEnumerable-to-Comma-Separated-List-(and-more).aspx

    A pet hate of mine when developing is making a list of comma separated ids, it is SO simple but always has ugly code.... Common solutions are to loop through and put a comma after each item then remove the last character, or to have an if statement to check if you at the begining or end of the list. Below is a solution you can use on any IEnumberable ie a List, Array etc. It is also the most efficient way I can think of doing it as it relies on assignment which is better than editing a string or using an if.

    public static class StringExtensions
    {
        public static string Splice<T>(IEnumerable<T> args, string delimiter)
        {
            StringBuilder sb = new StringBuilder();
            string d = "";
            foreach (T t in args)
            {
                sb.Append(d);
                sb.Append(t.ToString());
                d = delimiter;
            }
            return sb.ToString();
        }
    }
    

    Now it can be used with any IEnumerable eg.

    StringExtensions.Splice(billingTransactions.Select(t => t.id), ",")

    to give us 31,32,35

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