C# 与带有分隔符的 String.Split 相对 (.net)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/455438/
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
Opposite of String.Split with separators (.net)
提问by robintw
Is there a way to do the opposite of String.Split
in .Net? That is, to combine all the elements of an array with a given separator.
有没有办法String.Split
在 .Net 中做相反的事情?也就是说,将数组的所有元素与给定的分隔符组合在一起。
Taking ["a", "b", "c"]
and giving "a b c"
(with a separator of " "
).
接受["a", "b", "c"]
和给予"a b c"
(用 分隔符" "
)。
UPDATE:I found the answer myself. It is the String.Join
method.
更新:我自己找到了答案。这是String.Join
方法。
采纳答案by robintw
Found the answer. It's called String.Join.
找到了答案。它被称为String.Join。
回答by budi
You can use String.Join
:
您可以使用String.Join
:
string[] array = new string[] { "a", "b", "c" };
string separator = " ";
string joined = String.Join(separator, array); // "a b c"
Though more verbose, you can also use a StringBuilder
approach:
虽然更冗长,但您也可以使用一种StringBuilder
方法:
StringBuilder builder = new StringBuilder();
if (array.Length > 0)
{
builder.Append(array[0]);
}
for (var i = 1; i < array.Length; ++i)
{
builder.Append(separator);
builder.Append(array[i]);
}
string joined = builder.ToString(); // "a b c"