string 将字符串列表转换为由分隔符分隔的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/751881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert List of String to a String separated by a delimiter
提问by spacemonkeys
Whats the best way to convert a list(of string) to a string with the values seperated by a comma (,
)
将(字符串)列表转换为值以逗号 ( ,
)分隔的字符串的最佳方法是什么
回答by KevB
String.Join(",", myListOfStrings.ToArray())
回答by Guffa
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.
这取决于您所说的“最佳”是什么意思。内存占用最少的是首先计算最终字符串的大小,然后创建具有该容量的 StringBuilder 并将字符串添加到其中。
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.
StringBuilder 将创建一个具有正确大小的字符串缓冲区,该缓冲区是您从 ToString 方法中作为字符串获得的。这意味着没有创建额外的中间字符串或数组。
// 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();
回答by BurningKrome
My solution:
我的解决方案:
string = ["a","2"]\n
newstring = ""
endOfString = len(string)-1
for item in string:
newstring = newstring + item
if item != string[endOfString]:
newstring = newstring ","'
回答by Alex
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 (",")
它从字符串中取出第一个字符 (",")