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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 04:02:15  来源:igfitidea点击:

Opposite of String.Split with separators (.net)

c#.netarraysstring

提问by robintw

Is there a way to do the opposite of String.Splitin .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.Joinmethod.

更新:我自己找到了答案。这是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 StringBuilderapproach:

虽然更冗长,但您也可以使用一种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"