Join a string using delimiters

后端 未结 24 1607
北海茫月
北海茫月 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:37

    It's impossible to give a truly language-agnostic answer here as different languages and platforms handle strings differently, and provide different levels of built-in support for joining lists of strings. You could take pretty much identical code in two different languages, and it would be great in one and awful in another.

    In C#, you could use:

    StringBuilder builder = new StringBuilder();
    string delimiter = "";
    foreach (string item in list)
    {
        builder.Append(delimiter);
        builder.Append(item);
        delimiter = ",";       
    }
    return builder.ToString();
    

    This will prepend a comma on all but the first item. Similar code would be good in Java too.

    EDIT: Here's an alternative, a bit like Ian's later answer but working on a general IEnumerable.

    // Change to IEnumerator for the non-generic IEnumerable
    using (IEnumerator iterator = list.GetEnumerator())
    {
        if (!iterator.MoveNext())
        {
            return "";
        }
        StringBuilder builder = new StringBuilder(iterator.Current);
        while (iterator.MoveNext())
        {
            builder.Append(delimiter);
            builder.Append(iterator.Current);
        }
        return builder.ToString();
    }
    

    EDIT nearly 5 years after the original answer...

    In .NET 4, string.Join was overloaded pretty significantly. There's an overload taking IEnumerable which automatically calls ToString, and there's an overload for IEnumerable. So you don't need the code above any more... for .NET, anyway.

提交回复
热议问题