整型数组转换为字符串

81
在C#中,我有一个仅包含数字的int数组,我希望将该数组转换为字符串。
数组示例:
int[] arr = {0,1,2,3,0,1};

我该如何将它转换为格式为"012301"的字符串?

13个回答

1
最有效的方法不是将每个int转换为字符串,而是将一组字符创建为一个字符串。然后垃圾收集器只需要担心一个新的临时对象。
int[] arr = {0,1,2,3,0,1};
string result = new string(Array.ConvertAll<int,char>(arr, x => Convert.ToChar(x + '0')));

0
如果这是一个长数组,你可以使用:
var sb = arr.Aggregate(new StringBuilder(), ( s, i ) => s.Append( i ), s.ToString());

0
// This is the original array
int[] nums = {1, 2, 3};

// This is an empty string we will end up with
string numbers = "";

// iterate on every char in the array
foreach (var item in nums)
{
    // add the char to the empty string
    numbers += Convert.ToString(item);
}

// Write the string in the console
Console.WriteLine(numbers);

仅提供代码的答案并不是很有用。请解释您的代码。 - mousetail

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接