如何将 int[] 连接到 .NET 中的字符分隔字符串? [英] How can I join int[] to a character-separated string in .NET?
问题描述
我有一个整数数组:
int[] number = new int[] { 2,3,6,7 };
将这些转换为单个字符串的最简单方法是什么,其中数字由字符分隔(例如:"2,3,6,7"
)?
What is the easiest way of converting these into a single string where the numbers are separated by a character (like: "2,3,6,7"
)?
我使用的是 C# 和 .NET 3.5.
I'm using C# and .NET 3.5.
推荐答案
var ints = new int[] {1, 2, 3, 4, 5};
var result = string.Join(",", ints.Select(x => x.ToString()).ToArray());
Console.WriteLine(result); // prints "1,2,3,4,5"
从(至少).NET 4.5 开始,
As of (at least) .NET 4.5,
var result = string.Join(",", ints.Select(x => x.ToString()).ToArray());
相当于:
var result = string.Join(",", ints);
我看到一些解决方案宣传 StringBuilder 的使用.有人抱怨 Join 方法应该采用 IEnumerable 参数.
I see several solutions advertise usage of StringBuilder. Someone complains that the Join method should take an IEnumerable argument.
我会让你失望的 :) String.Join 需要一个数组,原因只有一个 - 性能.Join 方法需要知道数据的大小才能有效地预分配必要的内存量.
I'm going to disappoint you :) String.Join requires an array for a single reason - performance. The Join method needs to know the size of the data to effectively preallocate the necessary amount of memory.
这里是String.Join方法内部实现的一部分:
Here is a part of the internal implementation of String.Join method:
// length computed from length of items in input array and length of separator
string str = FastAllocateString(length);
fixed (char* chRef = &str.m_firstChar) // note than we use direct memory access here
{
UnSafeCharBuffer buffer = new UnSafeCharBuffer(chRef, length);
buffer.AppendString(value[startIndex]);
for (int j = startIndex + 1; j <= num2; j++)
{
buffer.AppendString(separator);
buffer.AppendString(value[j]);
}
}
这篇关于如何将 int[] 连接到 .NET 中的字符分隔字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!