[英]Convert String to 2D array in C#
我目前正在以字符串形式從客戶端計算機接收數據,但我希望它是[25,3]的2D數組。 因此,我首先將其拆分為單個數組,然后嘗試將該單個數組拆分為2D數組。 但是,當我運行代碼時,我不斷看到一個空數組,有人知道為什么嗎?
private void ClientReceiveData(object sender, ConnectedClient.NetDataEventArgs e)
{
if (string.IsNullOrEmpty(e.Message) == false)
{
if (e.ID == 0)
{
result = Array.ConvertAll(e.Message.Split(new[] { ',', }, StringSplitOptions.RemoveEmptyEntries), Double.Parse);
for (int i = 0; i < result.Length; i++)
{
resultarray2D[i % 3, i % 3] = result[i];
Trace.WriteLine(resultarray2D);
}
}
if (e.ID == 1)
{
answer = Array.ConvertAll(e.Message.Split(new[] { ',', }, StringSplitOptions.RemoveEmptyEntries), Double.Parse);
for (int i = 0; i < answer.Length; i++)
{
answerarray2D[i % 3, i / 3] = answer[i];
Trace.WriteLine(answerarray2D);
}
}
我一直看到一個空數組
不,您會看到數組上ToString
的默認輸出是什么,它是類的名稱。 如果要查看數組的內容 ,請遍歷並輸出各個項目:
int rowLength = arr.GetLength(0);
int colLength = arr.GetLength(1);
for (int i = 0; i < rowLength; i++)
{
for (int j = 0; j < colLength; j++)
{
Console.Write(string.Format("{0} ", arr[i, j]));
}
Console.WriteLine();
}
這應該起作用(我對上述人員的內容進行了一些更改,並在您的代碼中實現了它):
if (string.IsNullOrEmpty(e.Message) == false)
{
if (e.ID == 0)
{
result = Array.ConvertAll(e.Message.Split(new[] { ',', }, StringSplitOptions.RemoveEmptyEntries), Double.Parse);
for (int x = 0; x < result.Length; x++)
{
resultarray2D[x / 3, x % 3] = result[x];
}
int rowLength = resultarray2D.GetLength(0);
int colLength = resultarray2D.GetLength(1);
for (int i = 0; i < rowLength; i++)
{
for (int j = 0; j < colLength; j++)
{
Trace.WriteLine(string.Format("{0} ", resultarray2D[i, j]));
}
Trace.WriteLine("\n");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.