加盟字符串最efficent方式 [英] Most efficent way of joining strings
本文介绍了加盟字符串最efficent方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要产品总数串联了很多串,并把其中的任何中间用逗号分隔。
我有一个字符串
I need to concatenate a lot of strings alltogether and put a comma between any of them. I have a list of strings
"123123123213"
"1232113213213"
"123213123"
和我想要得到
"123123123213,1232113213213,123213123"
我想知道是什么。最好的方式来实现这一目标。
I was wondering what is the best way to achieve that.
我能做到这一点是这样的:
I could do this like this:
private List<string> stringList = new List<string> {
// a lot of strings in here
"1234567890", "34343434", "4343434" };
string outcome = string.Join(",", stringList.ToArray());
也许
Or maybe:
StringBuilder builder = new StringBuilder();
stringList.ForEach(val => {
builder.Append(val);
builder.Append(",");
});
string outcome = builder.ToString();
哪种方式更好?你知道更好的方法来连接字符串?
Which way is better? Do you know better ways to concatenate strings?
推荐答案
作为的 @ Ekkehard 说,使用串。加入。
不过,你不需要 ToArray的()
,因为的string.join
有的IEnumerable<字符串方式>
However, you do not need the ToArray()
because string.Join
has an overload for IEnumerable<string>
.
List<string> stringList = new List<string>
{ "1234567890", "34343434", "4343434" };
string outcome = string.Join(",", stringList);
修改
由于 @Kobi 说,这将工作仅C#4.0。在3.5,我会做
As @Kobi said, this will work only C# 4.0. In 3.5 I would do.
var s = new StringBuilder(stringList.Count * 8);
foreach (var item in stringList)
{
s.Append(item);
s.Append(',');
}
s.Length -= 1;
string outcome = stringList.ToList();
这篇关于加盟字符串最efficent方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文