如何在文本文件中存储一串数字,并将每个数字读取到数组索引中

本文关键字:数字 读取 索引 数组 文件 文本 存储 一串 | 更新日期: 2023-09-27 18:03:03

如果我有一个包含字符串的文本文件:100101101

我可以通过使用以下代码读取并存储它:

string text = System.IO.File.ReadAllText(@"writeText.txt");

如何将字符串转换为单独的数字并将每个数字添加到数组索引中,是否需要用逗号分隔每个数字?我在想,我可以迭代字符串,并将每个字符转换为整数并添加到数组中,这可行吗?

以下是我正在尝试的:

        int[] arrSetup = new int[9];
        string text = System.IO.File.ReadAllText(@"writeText.txt");
        foreach (char c in text)
        {
            arrSetup[0] = Int32.Parse(c);
        }

如何在文本文件中存储一串数字,并将每个数字读取到数组索引中

您的数据如下:100101101。。所以不需要用逗号分隔,然后将其添加到整数数组中。。。

所以,试着像下面这样,它会帮助你。。。

        string text = System.IO.File.ReadAllText(@"writeText.txt");
        int[] arr = new int[text.Length];
        for (int i = 0; i < text.Length; i++)
        {
            arr[i] = Convert.ToInt32(text[i].ToString());
        }

现在,整数数组arr[]分别具有值。。。

希望这会有所帮助,自己试试吧:

        string text = System.IO.File.ReadAllText(@"writeText.txt");
        char[] arr = text.ToCharArray() ;
        int[] nums = {0};
        for (int a = 0; a < 8; a++)
           nums[a] = System.Convert.ToInt32(arr[a]);