Join a string using delimiters

后端 未结 24 1649
北海茫月
北海茫月 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: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(this IEnumerable 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.

提交回复
热议问题