Join a string using delimiters

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

    In .NET, you can use the String.Join method:

    string concatenated = String.Join(",", list.ToArray());
    

    Using .NET Reflector, we can find out how it does it:

    public static unsafe string Join(string separator, string[] value, int startIndex, int count)
    {
        if (separator == null)
        {
            separator = Empty;
        }
        if (value == null)
        {
            throw new ArgumentNullException("value");
        }
        if (startIndex < 0)
        {
            throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
        }
        if (count < 0)
        {
            throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
        }
        if (startIndex > (value.Length - count))
        {
            throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
        }
        if (count == 0)
        {
            return Empty;
        }
        int length = 0;
        int num2 = (startIndex + count) - 1;
        for (int i = startIndex; i <= num2; i++)
        {
            if (value[i] != null)
            {
                length += value[i].Length;
            }
        }
        length += (count - 1) * separator.Length;
        if ((length < 0) || ((length + 1) < 0))
        {
            throw new OutOfMemoryException();
        }
        if (length == 0)
        {
            return Empty;
        }
        string str = FastAllocateString(length);
        fixed (char* chRef = &str.m_firstChar)
        {
            UnSafeCharBuffer buffer = new UnSafeCharBuffer(chRef, length);
            buffer.AppendString(value[startIndex]);
            for (int j = startIndex + 1; j <= num2; j++)
            {
                buffer.AppendString(separator);
                buffer.AppendString(value[j]);
            }
        }
        return str;
    }
    
    0 讨论(0)
  • 2020-12-05 10:51

    I thint the best way to do something like that is (I'll use pseudo-code, so we'll make it truly language agnostic):

    function concat(<array> list, <boolean> strict):
      for i in list:
        if the length of i is zero and strict is false:
          continue;
        if i is not the first element:
          result = result + separator;
        result = result + i;
      return result;
    

    the second argument to concat(), strict, is a flag to know if eventual empty strings have to be considered in concatenation or not.

    I'm used to not consider appending a final separator; on the other hand, if strict is false the resulting string could be free of stuff like "A,B,,,F", provided the separator is a comma, but would instead present as "A,B,F".

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

    In Clojure, you could just use clojure.contrib.str-utils/str-join:

    (str-join ", " list)
    

    But for the actual algorithm:

    (reduce (fn [res cur] (str res ", " cur)) list)
    
    0 讨论(0)
  • 2020-12-05 10:52

    I'd always add the delimeter and then remove it at the end if necessary. This way, you're not executing an if statement for every iteration of the loop when you only care about doing the work once.

    StringBuilder sb = new StringBuilder();
    
    foreach(string item in list){
        sb.Append(item);
        sb.Append(delimeter);
    }
    
    if (list.Count > 0) {
        sb.Remove(sb.Length - delimter.Length, delimeter.Length)
    }
    
    0 讨论(0)
  • 2020-12-05 10:54

    that's how python solves the problem:

    ','.join(list_of_strings)
    

    I've never could understand the need for 'algorithms' in trivial cases though

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

    Seen the Python answer like 3 times, but no Ruby?!?!?

    the first part of the code declares a new array. Then you can just call the .join() method and pass the delimiter and it will return a string with the delimiter in the middle. I believe the join method calls the .to_s method on each item before it concatenates.

    ["ID", "Description", "Active"].join(",")
    >> "ID, Description, Active"
    

    this can be very useful when combining meta-programming with with database interaction.

    does anyone know if c# has something similar to this syntax sugar?

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