Join a string using delimiters

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

    For java a very complete answer has been given in this question or this question.

    That is use StringUtils.join in Apache Commons

    String result = StringUtils.join(list, ", ");
    
    0 讨论(0)
  • 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<string>.

    // Change to IEnumerator for the non-generic IEnumerable
    using (IEnumerator<string> 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<T> which automatically calls ToString, and there's an overload for IEnumerable<string>. So you don't need the code above any more... for .NET, anyway.

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

    In PHP's implode():

    $string = implode($delim, $array);
    
    0 讨论(0)
  • 2020-12-05 10:37
    List<string> aaa = new List<string>{ "aaa", "bbb", "ccc" };
    string mm = ";";
    return aaa.Aggregate((a, b) => a + mm + b);
    

    and you get

    aaa;bbb;ccc
    

    lambda is pretty handy

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

    In .NET, I would use the String.join method if possible, which allows you to specify a separator and a string array. A list can be converted to an array with ToArray, but I don't know what the performance hit of that would be.

    The three algorithms that you mention are what I would use (I like the second because it does not have an if statement in it, but if the length is not known I would use the third because it does not duplicate the code). The second will only work if the list is not empty, so that might take another if statement.

    A fourth variant might be to put a seperator in front of every element that is concatenated and then remove the first separator from the result.

    If you do concatenate strings in a loop, note that for non trivial cases the use of a stringbuilder will vastly outperform repeated string concatenations.

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

    The problem is that computer languages rarely have string booleans, that is, methods that are of type string that do anything useful. SQL Server at least has is[not]null and nullif, which when combined solve the delimiter problem, by the way: isnotnull(nullif(columnvalue, ""),"," + columnvalue))

    The problem is that in languages there are booleans, and there are strings, and never the twain shall meet except in ugly coding forms, e.g.

    concatstring = string1 + "," + string2; if (fubar) concatstring += string3 concatstring += string4 etc

    I've tried mightily to avoid all this ugliness, playing comma games and concatenating with joins, but I'm still left with some of it, including SQL Server errors when I've missed one of the commas and a variable is empty.

    Jonathan

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