Convert List of String to a String separated by a delimiter

前端 未结 4 1944
心在旅途
心在旅途 2021-01-31 14:45

Whats the best way to convert a list(of string) to a string with the values seperated by a comma (,)

相关标签:
4条回答
  • 2021-01-31 15:19

    That depends on what you mean by "best". The least memory intensive is to first calculate the size of the final string, then create a StringBuilder with that capacity and add the strings to it.

    The StringBuilder will create a string buffer with the correct size, and that buffer is what you get from the ToString method as a string. This means that there are no extra intermediate strings or arrays created.

    // specify the separator
    string separator = ", ";
    
    // calculate the final length
    int len = separator.Length * (list.Count - 1);
    foreach (string s in list) len += s.Length;
    
    // put the strings in a StringBuilder
    StringBuilder builder = new StringBuilder(len);
    builder.Append(list[0]);
    for (int i = 1; i < list.Count; i++) {
       builder.Append(separator).Append(list[i]);
    }
    
    // get the internal buffer as a string
    string result = builder.ToString();
    
    0 讨论(0)
  • 2021-01-31 15:24
    String.Join(",", myListOfStrings.ToArray())
    
    0 讨论(0)
  • 2021-01-31 15:26

    My solution:

    string = ["a","2"]\n
    newstring = ""
    endOfString = len(string)-1
    for item in string:
        newstring = newstring + item
    if item != string[endOfString]:
        newstring = newstring ","'
    
    0 讨论(0)
  • 2021-01-31 15:26

    A simple solution:

    dim str as string = ""
    for each item as string in lst
      str += ("," & item)
    next
    return str.substring(1)
    

    It takes off the first char from the string (",")

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