我尋找一個簡單的方法來隱蔽二維字節[,]數組在C#一個字符串數組。
我發現函數
System.Text.Encoding.UTF8.GetString()
for convertig byte [] to string。
問題
- 但是對於2D字節做[,]數組到字符串數組。字節[,]的長度每次都不相同。
我尋找一個簡單的方法來隱蔽二維字節[,]數組在C#一個字符串數組。
我發現函數System.Text.Encoding.UTF8.GetString()
for convertig byte [] to string。
問題
byte[,] bytes = new byte[,] {
{ (byte)'H', (byte)'e', (byte)'l', (byte)'l', (byte)'o', (byte)'!' },
{ (byte)'W', (byte)'o', (byte)'r', (byte)'l', (byte)'d', (byte)0 }
};
string[] strings = new string[bytes.GetLength(0)];
for(var i = 0; i < bytes.GetLength(0); i++) {
byte[] stringBytes = bytes.OfType<byte>()
.Skip(i * bytes.GetLength(1))
.Take(bytes.GetLength(1))
.ToArray();
strings[i] = System.Text.Encoding.UTF8.GetString(stringBytes);
}
Test it online here。但是,如果類型是byte[][]
而不是byte[,]
,那麼對於您來說事情要容易得多......請您澄清爲什麼您使用byte[,]
?
說明:GetLength(int dimension)
返回指定尺寸的長度 - 在這種情況下,GetLength(0)
是2
(對於兩個串)和GetLength(1)
是6
(對於6串長度)。我們分配一個足夠大的字符串數組來保存我們所有的字符串。然後,對於每個單個字符串(在for
循環中),我們首先獲取屬於該字符串的所有字節。這是使用Linq完成的:我們將byte[,]
數組轉換爲一系列普通的byte
s(使用OfType
),然後我們將Skip
所有字節轉換成我們以前見過的所有字節,只有Take
儘可能多的byte
s。然後將這些byte
填充到臨時數組stringBytes
中,然後將其解碼爲字符串。
由於您可以遍歷包含數組的數組,因此鋸齒形數組要容易得多。對他們來說,你可能只是做了這樣的事情:
var stringArray = byteArrays
.Select(innerArray => Encoding.UTF8.GetString(innerArray))
.ToList();
但是既然不是這樣,我們需要想出不同的東西。多維數組更像是一個Excel電子表格,每個單元格包含一個字符。
問題在於每行都有完全相同的字節數量,而字符串可能有較小的大小。最標準的方法是用NULL(0)來終止字符串。
這是我的工作樣本:
class Program
{
static void Main(string[] args)
{
//different sizes for each row.
byte[,] arrays = new byte[2,40];
arrays[0,0] = (byte)'A';
arrays[0, 1] = (byte)'B';
arrays[0, 2] = (byte)'C';
arrays[0, 3] = (byte)'D';
arrays[1, 0] = (byte)'E';
arrays[1, 1] = (byte)'F';
arrays[1, 2] = (byte)'G';
arrays[1, 3] = (byte)'H';
arrays[1, 4] = (byte)'I';
List<string> stringArray = new List<string>();
List<byte> stringBytes = new List<byte>();
for (int row = 0; row < arrays.GetLength(0); row += 1)
{
for (int col = 0; col < arrays.GetLength(1); col += 1)
{
//got a null terminator
if (arrays[row, col] == 0)
{
//check if it's for UTF8 encoding.
if (arrays.GetLength(1) == col+1 || arrays[row,col+1] == 0)
{
//nope. End of this string.
stringArray.Add(Encoding.UTF8.GetString(stringBytes.ToArray()));
stringBytes.Clear();
break;
}
}
// add all bytes for the current row.
stringBytes.Add(arrays[row, col]);
}
}
foreach (var item in stringArray)
{
//prints:
// ABCD
// EFGHI
Console.WriteLine(item);
}
}
}
你在將其轉換爲字符串? –
請舉一個例子 –
你確定它不是byte [] []'數組嗎? – jgauffin