如何加入INT [],在.NET中的字符分隔字符串? [英] How to join int[] to a character separated string in .NET?

查看:280
本文介绍了如何加入INT [],在.NET中的字符分隔字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数数组: INT []号=新INT [] {2,3,6,7};

什么是的在将这些到数由字符分隔一个字符串的(如最简单的方法:2,3,4,7)?

我在C#和.NET 3.5。

解决方案

  VAR整数=新INT [] {1,2,3,4,5};
变种结果=的string.join(,,ints.Select(X => x.ToString())的ToArray());
Console.WriteLine(结果); //输出1,2,3,4,5
 

修改

我看到了几种解决方案做广告的StringBuilder的使用。有人抱怨,加入方法应该采取一个IEnumerable参数。

我要你们失望了:)的string.join需要数组,理由只有一个 - 性能。联接方法需要知道数据的大小,以有效地$的内存不足p $ pallocate必要量

下面是的string.join方法的内部实现的一部分:

  //长度从输入数组和分离器的长度的项目长度计算
字符串str = FastAllocateString(长度);
固定(字符* chRef =安培; str.m_firstChar)//注意比我们使用直接内存访问这里
{
    UnSafeCharBuffer缓冲=新UnSafeCharBuffer(chRef,长度);
    buffer.AppendString(值[在startIndex]);
    对于(INT J =在startIndex + 1; J< = NUM​​2; J ++)
    {
        buffer.AppendString(分隔符);
        buffer.AppendString(价值[J]);
    }
}
 

我懒得比较的建议方法的性能。但直觉告诉我,加入赢:)

I have a array of integers: int [] number = new int[] { 2,3,6,7 };

What is the easiest way of converting these in to a single string where the number are separated by a character (like: "2,3,4,7")?

I'm in 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"

EDIT:

I see several solutions advertise usage of StringBuilder. Someone complaints that Join method should take an IEnumerable argument.

I'm going to disappoint you :) String.Join requires array for a single reason - performance. Join method needs to know the size of the data to effectively preallocate necessary amount of memory.

Here is a part of 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]);
    }
}

I'm too lazy to compare performance of suggested methods. But something tells me that Join will win :)

这篇关于如何加入INT [],在.NET中的字符分隔字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆