C# int 数组到字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1822811/
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-06 21:08:14  来源:igfitidea点击:

int array to string

c#arraysstring

提问by user397232

In C#, I have an array of ints, containing digits only. I want to convert this array to string.

在 C# 中,我有一个整数数组,仅包含数字。我想将此数组转换为字符串。

Array example:

数组示例:

int[] arr = {0,1,2,3,0,1};

How can I convert this to a string formatted as: "012301"?

如何将其转换为格式为:的字符串"012301"

回答by JSB????

at.net 3.5 use:

at.net 3.5 使用:

 String.Join("", new List<int>(array).ConvertAll(i => i.ToString()).ToArray());

at.net 4.0 or above use: (see @Jan Remunda's answer)

at.net 4.0 或更高版本使用:(见@Jan Remunda 的回答)

 string result = string.Join("", array);

回答by mqp

string result = arr.Aggregate("", (s, i) => s + i.ToString());

(Disclaimer: If you have a lot of digits (hundreds, at least) and you care about performance, I suggest eschewing this method and using a StringBuilder, as in JaredPar's answer.)

(免责声明:如果您有很多数字(至少是数百个)并且您关心性能,我建议避免使用这种方法并使用 a StringBuilder,如 JaredPar 的回答。)

回答by Reed Copsey

You can do:

你可以做:

 int[] arr = {0,1,2,3,0,1};
 string results = string.Join("",arr.Select(i => i.ToString()).ToArray());

That gives you your results.

这给你你的结果。

回答by Paul Ruane

I've left this here for posterity but don't recommend its use as it's not terribly readable. This is especially true now that I've come back to see if after a period of some time and have wondered what I was thinking when I wrote it (I was probably thinking 'crap, must get this written before someone else posts an answer'.)

我把它留在这里供后代使用,但不建议使用它,因为它的可读性不是很强。现在尤其如此,因为一段时间后我回来看看是否并想知道我在写它时在想什么(我可能在想'废话,必须在其他人发布答案之前写下这个' .)

string s = string.Concat(arr.Cast<object>().ToArray());

回答by JaredPar

To avoid the creation of an extra array you could do the following.

为了避免创建额外的数组,您可以执行以下操作。

var builder = new StringBuilder();
Array.ForEach(arr, x => builder.Append(x));
var res = builder.ToString();

回答by Michael Damatov

string.Join("", (from i in arr select i.ToString()).ToArray())

In the .NET 4.0 the string.Joincan use an IEnumerable<string>directly:

在 .NET 4.0 中string.Join可以IEnumerable<string>直接使用:

string.Join("", from i in arr select i.ToString())

回答by Danko Durbi?

I like using StringBuilderwith Aggregate(). The "trick" is that Append()returns the StringBuilderinstance itself:

我喜欢StringBuilderAggregate(). “技巧”是Append()返回StringBuilder实例本身:

var sb = arr.Aggregate( new StringBuilder(), ( s, i ) => s.Append( i ) );
var result = sb.ToString();     

回答by Dr. Wily's Apprentice

I realize my opinion is probably not the popular one, but I guess I have a hard time jumping on the Linq-y band wagon. It's nifty. It's condensed. I get that and I'm not opposed to using it where it's appropriate. Maybe it's just me, but I feel like people have stopped thinking about creating utility functions to accomplish what they want and instead prefer to litter their code with (sometimes) excessively long lines of Linq code for the sake of creating a dense 1-liner.

我意识到我的观点可能不是流行的,但我想我很难跳上 Linq-y 乐队的旅行车。它很漂亮。是浓缩的。我明白这一点,我不反对在适当的地方使用它。也许只是我,但我觉得人们已经不再考虑创建实用函数来完成他们想要的东西,而是更喜欢用(有时)过长的 Linq 代码行乱扔他们的代码,以便创建一个密集的 1-liner。

I'm not saying that any of the Linq answers that people have provided here are bad, but I guess I feel like there is the potential that these single lines of code can start to grow longer and more obscure as you need to handle various situations. What if your array is null? What if you want a delimited string instead of just purely concatenated? What if some of the integers in your array are double-digit and you want to pad each value with leading zeros so that the string for each element is the same length as the rest?

我并不是说人们在这里提供的任何 Linq 答案都不好,但我想我觉得这些单行代码有可能随着您需要处理各种情况而变得越来越长、越来越模糊. 如果您的数组为空怎么办?如果你想要一个分隔的字符串而不是纯粹的连接怎么办?如果数组中的某些整数是两位数,并且您想用前导零填充每个值,以便每个元素的字符串与其余元素的长度相同,该怎么办?

Taking one of the provided answers as an example:

以提供的答案之一为例:

        result = arr.Aggregate(string.Empty, (s, i) => s + i.ToString());

If I need to worry about the array being null, now it becomes this:

如果我需要担心数组为空,现在它变成了这样:

        result = (arr == null) ? null : arr.Aggregate(string.Empty, (s, i) => s + i.ToString());

If I want a comma-delimited string, now it becomes this:

如果我想要一个逗号分隔的字符串,现在它变成了这样:

        result = (arr == null) ? null : arr.Skip(1).Aggregate(arr[0].ToString(), (s, i) => s + "," + i.ToString());

This is still not too bad, but I think it's not obvious at a glance what this line of code is doing.

这还不算太糟糕,但我认为这行代码在做什么,一目了然。

Of course, there's nothing stopping you from throwing this line of code into your own utility function so that you don't have that long mess mixed in with your application logic, especially if you're doing it in multiple places:

当然,没有什么能阻止您将这行代码放入您自己的实用程序函数中,这样您就不会在应用程序逻辑中混入那么长的混乱,尤其是当您在多个地方执行此操作时:

    public static string ToStringLinqy<T>(this T[] array, string delimiter)
    {
        // edit: let's replace this with a "better" version using a StringBuilder
        //return (array == null) ? null : (array.Length == 0) ? string.Empty : array.Skip(1).Aggregate(array[0].ToString(), (s, i) => s + "," + i.ToString());
        return (array == null) ? null : (array.Length == 0) ? string.Empty : array.Skip(1).Aggregate(new StringBuilder(array[0].ToString()), (s, i) => s.Append(delimiter).Append(i), s => s.ToString());
    }

But if you're going to put it into a utility function anyway, do you really need it to be condensed down into a 1-liner? In that case why not throw in a few extra lines for clarity and take advantage of a StringBuilder so that you're not doing repeated concatenation operations:

但是如果你无论如何都要把它放到一个效用函数中,你真的需要把它压缩成一个 1-liner 吗?在这种情况下,为什么不为了清楚起见多加几行并利用 StringBuilder 来避免重复连接操作:

    public static string ToStringNonLinqy<T>(this T[] array, string delimiter)
    {
        if (array != null)
        {
            // edit: replaced my previous implementation to use StringBuilder
            if (array.Length > 0)
            {
                StringBuilder builder = new StringBuilder();

                builder.Append(array[0]);
                for (int i = 1; i < array.Length; i++)
                {
                    builder.Append(delimiter);
                    builder.Append(array[i]);
                }

                return builder.ToString()
            }
            else
            {
                return string.Empty;
            }
        }
        else
        {
            return null;
        }
    }

And if you're really so concerned about performance, you could even turn it into a hybrid function that decides whether to do string.Join or to use a StringBuilder depending on how many elements are in the array (this is a micro-optimization, not worth doing in my opinion and possibly more harmful than beneficial, but I'm using it as an example for this problem):

如果你真的很关心性能,你甚至可以把它变成一个混合函数,根据数组中有多少元素来决定是执行 string.Join 还是使用 StringBuilder(这是一个微优化,在我看来不值得这样做,而且可能弊大于利,但我将其用作此问题的示例):

    public static string ToString<T>(this T[] array, string delimiter)
    {
        if (array != null)
        {
            // determine if the length of the array is greater than the performance threshold for using a stringbuilder
            // 10 is just an arbitrary threshold value I've chosen
            if (array.Length < 10)
            {
                // assumption is that for arrays of less than 10 elements
                // this code would be more efficient than a StringBuilder.
                // Note: this is a crazy/pointless micro-optimization.  Don't do this.
                string[] values = new string[array.Length];

                for (int i = 0; i < values.Length; i++)
                    values[i] = array[i].ToString();

                return string.Join(delimiter, values);
            }
            else
            {
                // for arrays of length 10 or longer, use a StringBuilder
                StringBuilder sb = new StringBuilder();

                sb.Append(array[0]);
                for (int i = 1; i < array.Length; i++)
                {
                    sb.Append(delimiter);
                    sb.Append(array[i]);
                }

                return sb.ToString();
            }
        }
        else
        {
            return null;
        }
    }

For this example, the performance impact is probably not worth caring about, but the point is that if you are in a situation where you actually do need to be concerned with the performance of your operations, whatever they are, then it will most likely be easier and more readable to handle that within a utility function than using a complex Linq expression.

对于这个例子,性能影响可能不值得关心,但关键是,如果你真的需要关心你的操作的性能,不管它们是什么,那么它很可能是与使用复杂的 Linq 表达式相比,在实用程序函数中处理它更容易、更易读。

That utility function still looks kind of clunky. Now let's ditch the hybrid stuff and do this:

那个效用函数看起来仍然有点笨拙。现在让我们放弃混合的东西并执行以下操作:

    // convert an enumeration of one type into an enumeration of another type
    public static IEnumerable<TOut> Convert<TIn, TOut>(this IEnumerable<TIn> input, Func<TIn, TOut> conversion)
    {
        foreach (TIn value in input)
        {
            yield return conversion(value);
        }
    }

    // concatenate the strings in an enumeration separated by the specified delimiter
    public static string Delimit<T>(this IEnumerable<T> input, string delimiter)
    {
        IEnumerator<T> enumerator = input.GetEnumerator();

        if (enumerator.MoveNext())
        {
            StringBuilder builder = new StringBuilder();

            // start off with the first element
            builder.Append(enumerator.Current);

            // append the remaining elements separated by the delimiter
            while (enumerator.MoveNext())
            {
                builder.Append(delimiter);
                builder.Append(enumerator.Current);
            }

            return builder.ToString();
        }
        else
        {
            return string.Empty;
        }
    }

    // concatenate all elements
    public static string ToString<T>(this IEnumerable<T> input)
    {
        return ToString(input, string.Empty);
    }

    // concatenate all elements separated by a delimiter
    public static string ToString<T>(this IEnumerable<T> input, string delimiter)
    {
        return input.Delimit(delimiter);
    }

    // concatenate all elements, each one left-padded to a minimum length
    public static string ToString<T>(this IEnumerable<T> input, int minLength, char paddingChar)
    {
        return input.Convert(i => i.ToString().PadLeft(minLength, paddingChar)).Delimit(string.Empty);
    }

Now we have separate and fairly compact utility functions, each of which are arguable useful on their own.

现在我们有了独立且相当紧凑的效用函数,每个函数都可以单独使用。

Ultimately, my point is not that you shouldn't use Linq, but rather just to say don't forget about the benefits of creating your own utility functions, even if they are small and perhaps only contain a single line that returns the result from a line of Linq code. If nothing else, you'll be able to keep your application code even more condensed than you could achieve with a line of Linq code, and if you are using it in multiple places, then using a utility function makes it easier to adjust your output in case you need to change it later.

最终,我的观点不是你不应该使用 Linq,而是说不要忘记创建自己的实用程序函数的好处,即使它们很小并且可能只包含一行返回结果一行 Linq 代码。如果不出意外,您将能够使您的应用程序代码比使用一行 Linq 代码更简洁,如果您在多个地方使用它,那么使用实用函数可以更轻松地调整您的输出以防您以后需要更改它。

For this problem, I'd rather just write something like this in my application code:

对于这个问题,我宁愿在我的应用程序代码中写这样的东西:

        int[] arr = { 0, 1, 2, 3, 0, 1 };

        // 012301
        result = arr.ToString<int>();

        // comma-separated values
        // 0,1,2,3,0,1
        result = arr.ToString(",");

        // left-padded to 2 digits
        // 000102030001
        result = arr.ToString(2, '0');

回答by Jeffrey L Whitledge

The most efficient way is not to convert each int into a string, but rather create one string out of an array of chars. Then the garbage collector only has one new temp object to worry about.

最有效的方法不是将每个 int 转换为字符串,而是从字符数组中创建一个字符串。那么垃圾收集器只需要担心一个新的临时对象。

int[] arr = {0,1,2,3,0,1};
string result = new string(Array.ConvertAll<int,char>(arr, x => Convert.ToChar(x + '0')));

回答by Jan Remunda

You can simply use String.Joinfunction, and as separator use string.Emptybecause it uses StringBuilderinternally.

您可以简单地使用String.Join函数,并作为分隔符使用,string.Empty因为它在StringBuilder内部使用。

string result = string.Join(string.Empty, new []{0,1,2,3,0,1});

E.g.: If you use semicolon as separator, the result would be 0;1;2;3;0;1.

例如:如果您使用分号作为分隔符,结果将是0;1;2;3;0;1.

It actually works with null separator, and second parameter can be enumerable of any objects, like:

它实际上适用于空分隔符,第二个参数可以枚举任何对象,例如:

string result = string.Join(null, new object[]{0,1,2,3,0,"A",DateTime.Now});