使用 C# 将文本文件传递到 int 或数组中

本文关键字:int 数组 文本 文件 使用 | 更新日期: 2023-09-27 18:35:25

我对 C# 编程相当陌生,我在过去一周开始学习它,我在将程序的两个部分连接在一起时遇到了问题。我站在哪里,我让它从文本文件中读取信息,然后我需要将信息传递给 ints 中,以便程序的主要部分使用和运行其功能。 基本上文本文件看起来像这样

30 3 5

100 7 16

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

但是对于每组数字,我需要将它们设置在我可以传递给我的整数 X Y 和 Z 的位置,这些整数是在文本文件运行后声明的,如果需要的话。我目前唯一的想法是将它们传递到数组中并调用 int(我可以做 int x = arr[1];如果我编码正确的话),但我没有运气将它们放入数组,更不用说单独调用它们了。

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

使用 C# 将文本文件传递到 int 或数组中

你可以

这样做。但是,您需要根据您的需要对其进行处理以使其更合适:我可以承认您需要在下面的代码中进行更多错误处理,例如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; }
    }

因此,请告诉我这是否对您有帮助。

试试这个:

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  
}