我有一个带有以下数字的文本文件,例如:
1 2 3
4 5 6
如何将每个单独的数字读入数组?
它需要沿着每一行移动,因此在1,2和3中读入一个数组然后移动到第二行并读取4 5和6 ..并显示文本框中的单元格数。
这是我的代码,但是我收到了错误。
List<string> list2 = new List<string>();
for (int i = 0; i < lines.Length; i++)
{
char[] chars = lines[i].ToCharArray();
for (int j = 0; j < chars.Length; j++)
{
if (!Char.IsWhiteSpace(chars[j]))
list2.Add(chars[j].ToString());
}
}
答案 0 :(得分:0)
您可以将其转换为锯齿状的int数组:
int[][] result = text
.Split('\n')
.Select(line =>
line
.Split(' ')
.Select(numberText => int.Parse(numberText))
.ToArray()).ToArray();
像这样迭代:
foreach (int[] line in result)
{
Console.WriteLine(string.Join(", ", line)); // or iterate through its numbers again
// or whatever you want to do
}
修改强>
List<string> list2 = new List<string>();
string path = "xy"; //your path
string[] lines = File.ReadAllLines(path);
int[][] result = lines
.Select(line =>
line
.Split(' ')
.Select(numberText => int.Parse(numberText))
.ToArray()).ToArray();
foreach (int[] line in result)
{
list2.Add(string.Join(", ", line)); // or whatever format you want the text to be
}
答案 1 :(得分:0)
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
label3.Text = openFileDialog1.FileName;
textBox1.Text = File.ReadAllText(label3.Text);
FileStream fs = File.OpenRead(label3.Text);
string[] lines = new StreamReader(fs).ReadToEnd().Split(new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
fs.Close();
List<string> list2 = new List<string>();
for (int i = 0; i < lines.Length; i++)
{
char[] chars = lines[i].ToCharArray();
for (int j = 0; j < chars.Length; j++)
{
if (!Char.IsWhiteSpace(chars[j]))
list2.Add(chars[j].ToString());
}
}
}