Reputation:
I clearly have no idea how to do this and not getting a whole lot of help from teachers. I have instructions to:
Part A: Read File into Array Read a text file of strings into a string array. Create the array bigger than the file. Count how many strings are in the array.
Part B: Enter String into Array Input a string from a text box. Assign the string into the first empty array element. Update the count of strings in the array.
Part C: Display Array in List Box Display the strings from the array in a list box. Don’t display unused array elements (more than the count).
Write Array to File Write the strings from the array to a text file
I'm not sure how to write any of this and the furthest I have gotten is here which is wrong and messy. Any help would be appreciated.
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);
}
}
Upvotes: 1
Views: 1433
Reputation: 360
I'll try to suggest step by step.
Here's the text file that we'll be reading.
This is one line.
This is a second line.
Finally, a third line.
First, here's we'll want to make a method for reading a file into a collection. Let's open a file as stream, read the file line-by-line and return the results in an IEnumerable where each string is a line.
/// <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();
}
Let's test that this works.
foreach (var line in GetFileLines(@"c:\test.txt")) Console.WriteLine(line);
Alright now, let's turn this into getting the lines into an object we can manipulate. I would suggest using a List since you can add items to it without defining the size beforehand.
// 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();
If you really want to stick only to using arrays, in order to create an array that is bigger than the number of lines, you'll need to do something like the following:
// 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];
PART B: I'm not completely sure what you're trying to do here, but let me make take a stab anyways. If you want to take a string that was entered into an input, and split it into an array of individual strings, that represent each word for instance:
// 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);
If you want, you can also split the text into a list instead of an array so that you can add, sort things easier, just as we did in the file example. Remember that you can convert the List back to an array with .ToArray() at any time.
var wordList = textFromInput.Split(' ').ToList();
PART C: To put a collection of words/lines, read from either a text box or a file, into a list is pretty straight forward. Use a combination of what we've covered so far:
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;
}
If you're attempting to filter out any items in the array that are just blank lines, or are just empty (all spaces), and you don't want empty entries in your list view:
// 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));
To write an array of words to a file:
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);
}
Upvotes: 3