假设txt文档中的二维数组如下:
123,121 |141
12 | | 12
12 | 123 |234
23 | 12 |123 | 123
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
char[] chspilt = new char[] { ',','|',' '};
string[,] temp = new string[4,4];
try
{
using (StreamReader sr = new StreamReader(@"C:\Users\wang\Desktop\新建文本文档.txt"))
{
int i = 0;
while (sr.Peek() != -1)
{
string temp1 = sr.ReadLine();
string[] split = temp1.Split(chspilt,StringSplitOptions.RemoveEmptyEntries);
int count;
count = split.Length;
switch (count)
{
case 4:
for(int j=0;j<count;j++)
{
temp[i, j] = split[j];
}
break;
case 3 :
for (int j = 0; j < count; j++)
{
temp[i, j] = split[j];
}
break;
case 2:
temp[i, 0] = split[0];
temp[i, 3] = split[1];
break;
}
i++;
}
}
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
//显示读取的二维数组
int pCount = 0;
for(int i=0;i<temp.GetLength(0);i++)
{
for(int j=0;j<temp.GetLength(1);j++)
{
if (temp[i, j] == null)
{
Console.Write("\t");
}
else
{
Console.Write(temp[i,j]+"\t");
}
pCount++;
if (pCount == 4)
{
Console.WriteLine();
pCount = 0;
}
}
}
Console.ReadLine();
}
}
}
注意:char[] chspilt = new char[] { ',','|',' '}; // 遇到char[]中的字符时进行分割。
string[] split = temp1.Split(chspilt,StringSplitOptions.RemoveEmptyEntries);忽略空格