将文件读入数组并将字符串输入数组

时间:2019-06-12 00:08:07

标签: c#

我显然不知道该怎么做,也没有得到老师的大量帮助。我有以下指示:

A部分:将文件读入数组 将字符串的文本文件读取到字符串数组中。 创建比文件大的数组。 计算数组中有多少个字符串。

B部分:将字符串输入数组 在文本框中输入字符串。 将字符串分配给第一个空数组元素。 更新数组中的字符串计数。

C部分:在列表框中显示数组 在列表框中显示数组中的字符串。 不要显示未使用的数组元素(多于计数)。

将数组写入文件 将数组中的字符串写入文本文件

我不确定如何写这些内容,而我得到的最大的错误和混乱是在这里。任何帮助将不胜感激。

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private string ReadStringFile(
            string fileName,    //name of file to read
            string[] contents,   //array to store strings
            int max)            //size of array
        {
            //Variables
            int count;  //count of numbers

            //Catch exceptions
            try
            {
                StreamReader stringFile = File.OpenText(fileName);

                //Read strings from file
                count = 0;
                while (!stringFile.EndOfStream && count < max)
                {
                    contents[count] = stringFile.ReadLine();
                    count++;
                }
                //Close file
                stringFile.Close();

                //Return to user
                return count.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Sorry, error reading file: " + ex.Message);
                return "";
            }
        }
        private void DisplayStrings(string[] contents, int count)
        {
            //Display strings in list box
            for (int i = 0; i < count; i++)
            {
                stringListBox.Items.Add(contents[i]);
            }
        }
        private void ProcessButton_Click(object sender, EventArgs e)
        {
            //Variables
            string fileName = "strings.txt";
            const int SIZE = 5;
            string[] contents = new string[SIZE];
            int count;

            ReadStringFile(fileName, contents, SIZE);

            DisplayStrings(contents, count);
        }
    }

1 个答案:

答案 0 :(得分:3)

我将尝试逐步建议。

这是我们将要阅读的文本文件。

This is one line.
This is a second line.
Finally, a third line.

首先,这是我们想要的一种将文件读取到集合中的方法。 让我们以流的形式打开文件,逐行读取文件,然后将结果返回到IEnumerable中,其中每个字符串都是一行。

/// <summary>
///     Creates an enumeration of every line in a file.
/// </summary>
/// <param name="filePath">Path to file.</param>
/// <returns>Enumeration of lines in specified file.</returns>
private IEnumerable<string> GetFileLines(string filePath)
{
    // Open the file.
    var fileStream = new System.IO.StreamReader(filePath);

    // Read each line.
    string line;
    while ((line = fileStream.ReadLine()) != null) yield return line;

    // Shut it down!
    fileStream.Close();
}

让我们测试一下。

foreach (var line in GetFileLines(@"c:\test.txt")) Console.WriteLine(line);

enter image description here

现在,让我们将其转换为将线放入可以操纵的对象中。我建议使用列表,因为您可以在不预先定义大小的情况下向其中添加项目。

// Get lines as list.
var lines = GetFileLines(@"c:\test.txt").ToList();

// How many lines are there?
var numberOfLines = lines.Count;

// Add a new line.
lines.Add("This is another line we are adding to our list");

// If you want it as an array, make an array from the list after manipulating
var lineArray = lines.ToArray();

如果您真的只想使用数组,则要创建一个大于行数的数组,您将需要执行以下操作:

// Get lines as an array and count lines.
var lines = GetFileLines(@"c:\test.txt").ToArray();
var numberOfLines = lines.Length;

// Decide how many additional lines we want and make our new array.
var newArraySize = lines.Length + 10; // Let's add 10 to our current length
var newArray = new string[newArraySize];

// Fill new array with our lines.
for (var i = 0; i < numberOfLines; i++) newArray[i] = lines[i];

B部分:我不确定您要在这里做什么,但是无论如何我还是要me一口。如果要采用输入到输入中的字符串,然后将其拆分为单个字符串的数组,例如代表每个单词的

// Get the text from input and create an array from each word.
var textFromInput = "This is just some text that the user entered.";
var words = textFromInput.Split(' ');

foreach(var word in words) Console.WriteLine(word);

enter image description here

如果需要,还可以将文本拆分为列表而不是数组,以便您可以像在文件示例中一样添加,排序内容。请记住,您可以随时使用.ToArray()将列表转换回数组。

var wordList = textFromInput.Split(' ').ToList();

部分C:要将单词/行的集合(从文本框或文件中读取)放入列表中,很简单。结合使用我们到目前为止介绍的内容:

private void Button1_Click(object sender, EventArgs e)
{
    // Get words from textbox as an array.
    var words = textBox1.Text.Split(' ');

    // Set the data source for the list box.
    // DataSource can be an array or a list (any enumerable), so use whichever you prefer.
    listBox1.DataSource = words;
}

enter image description here

如果您试图过滤掉数组中任何仅是空行或仅是空(所有空格)的项目,并且您不希望列表视图中有空条目:

// Get lines as list.
var lines = GetFileLines(@"c:\test.txt").ToList();

// Let's say that there were a few empty lines in the list.
for (var i = 0; i < 5; i++) lines.Add(""); // Add a few empty lines.

// Now, set the data source, and filter out the null/empty lines
listBox1.DataSource = lines.Where(x => !string.IsNullOrEmpty(x));

// ...

// Or maybe you are interested in removing empty and just whitespace
for (var i = 0; i < 5; i++) lines.Add("     "); // Add a few spaced lines
listBox1.DataSource = lines.Where(x => !string.IsNullOrWhiteSpace(x));

要将单词数组写入文件:

private void Button1_Click(object sender, EventArgs e)
{
    // Get words from textbox as an array.
    var words = textBox1.Text.Split(' ');

    // Write the words to a text file, with each item on it's own line
    System.IO.File.WriteAllLines(@"c:\test.txt", words);
}

enter image description here enter image description here