使用c#将文本文件传递给int或数组

时间:2014-12-26 19:00:43

标签: c# parsing text-files

我是C#编程的新手,我在过去的一周里接受了它,并且我在将程序的两个部分连接在一起时遇到了问题。我站在哪里,我从文本文件中读取信息,然后我需要将信息传递给程序主要部分的int,以便使用和运行其功能。基本上文本文件看起来像这样

30 3 5

100 7 16

等.... 每组数字都是3组,只是为了澄清我是否解释得不够好。

但是对于每组数字我需要它们设置在哪里我可以传递给我在运行文本文件后声明的X Y和Z,如果需要的话。我此刻唯一的想法是将它们传递给一个数组并调用int(我可以做int x = arr [1];如果我编码正确的话)那样但我没有运气让他们进入数组更不用说单独调用它们了。

我更愿意听取其他选项,但有人可以帮助并解释如何在代码部分完成它我想了解每一步发生的事情。

2 个答案:

答案 0 :(得分:1)

你可以这样做。但是,您需要根据自己的需要进行更合适的工作: 我可以承认,您需要在我的以下代码中执行更多错误处理,例如Convert.ToInt32部分

           public void XYZFile()
           {
                List<XYZ> xyzList = new List<XYZ>();
                string[] xyzFileContant = File.ReadAllLines(Server.MapPath("~/XYZ.txt"));
                //int lineCount = xyzFileContant.Length;
                foreach (string cont in xyzFileContant)
                {
                    if (!String.IsNullOrWhiteSpace(cont))
                    {
                        string[] contSplit = cont.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                        xyzList.Add(new XYZ
                                            {
                                                X = Convert.ToInt32(contSplit[0]),
                                                Y = Convert.ToInt32(contSplit[1]),
                                                Z = Convert.ToInt32(contSplit[2])
                                            }
                            );
                    }
                }
            }



    public class XYZ
    {
        public int X { get; set; }
        public int Y { get; set; }
        public int Z { get; set; }
    }

所以,请告诉我这是否有帮助。

答案 1 :(得分:0)

试试这个:

static int[] parse(string st)//let st be "13 12 20"
{
    int[] a = new int[3];
    a[0] = int.Parse(st.Substring(0, st.IndexOf(' ')));//this will return 13, indexof means where is the space, substring take a portion from the sting
    st = st.Remove(0, st.IndexOf(' ') + 1);//now remove the first number so we can get the second, st will be "12 20"
    a[1] = int.Parse(st.Substring(0, st.IndexOf(' ')));//second number
    st = st.Remove(0, st.IndexOf(' ') + 1);//st="20"
    a[2] = int.Parse(st);//all we have is the last number so all string is needed(no substring)
    return a;
}

此方法解析字符串并从中获取三个整数并将它们存储在一个数组中,然后返回此数组。我们将使用它来解析文本文件的行,如下所示:

static void Main(string[] args)
{
    StreamReader f = new StreamReader("test.txt");//the file
    int x, y, z;
    while (!f.EndOfStream)//stop when we reach the end of the file
    {
        int[] a = parse(f.ReadLine());//read a line from the text file and parse it to an integer array(using parse which we defined)
        x = a[0];//get x
        y = a[1];//get y
        z = a[2];//get z
        //do what you want with x and y and z here I'll just print them
        Console.WriteLine("{0} {1} {2}", x, y, z);
    }
    f.Close();          //close the file when finished  
}