简体   繁体   English

在C#中将int数组转换为字符串

[英]Convert int array to string in C#

I have an int[] : 我有一个int[]

RXBuffer[0], RXBuffer[1],..., RXBuffer[9]

where each value represents an ASCII code, so 0x31 represents 1 , 0x41 represents A . 其中,每个值表示成ASCII码,所以0X31表示1 ,0×41表示A

How do I convert this to a 10 character string ? 如何将其转换为10个字符串?

So far I've tried Data = RxBuffer.ToString(); 到目前为止,我已经尝试过Data = RxBuffer.ToString(); . But it shows Data equals to System.Int32[] which is not what my data is. 但是它显示Data等于System.Int32[] ,这不是我的数据。

How can I do this? 我怎样才能做到这一点?

Assuming the "int array" is values in the 0-9 range (which is the only way that makes sense to convert an "int array" length 10 to a 10-character string) - a bit of an exotic way: 假设“整数数组”的值在0-9范围内(这是将“整数数组”的长度10转换为10个字符的字符串的唯一方法)-有点奇怪:

string s = new string(Array.ConvertAll(RXBuffer, x => (char)('0' + x)));

But pretty efficient (the char[] is right-sized automatically, and the string conversion is done just with math, instead of ToString() ). 但是效率很高( char[]自动自动调整大小,并且字符串转换仅通过数学运算而不是ToString() )。


Edit: with the revision that makes it clear that these are actually ASCII codes, it becomes simpler: 编辑:修订版可以清楚地表明它们实际上是ASCII码,因此变得更加简单:

string s = new string(Array.ConvertAll(RXBuffer, x => (char)x));

Although frankly, if the values are ASCII (or even unicode) it would be better to store it as a char[] ; 坦白地说,如果值是ASCII(甚至是unicode),最好将其存储为char[] this covers the same range, takes half the space, and is just: 它覆盖相同的范围,占用一半的空间,只是:

string s = new string(RXBuffer);

LolCoder All you need is : LolCoder所有您需要的是:

string.Join("",RXBuffer);

============== Or ================= =============或=================

        int[] RXBuffer = {0,1,2,3,4,5,6,7,8,9};
        string result  =  string.Join(",",RXBuffer);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM