cotj73
asked on
Input text file to an array
I am attempting to read a file in, and throw the contents into a matrix, where each element is stored in a different container
Example
Text File
123
456
789
Matrix
{{1,2,3}
{4,5,6}
{7,8,9}}
I am using stream reader to read the contents in, and know how to pull the contents into an array, but not a Matrix
Example
Text File
123
456
789
Matrix
{{1,2,3}
{4,5,6}
{7,8,9}}
I am using stream reader to read the contents in, and know how to pull the contents into an array, but not a Matrix
If you are referring how to convert a string to an array:
string str = "abcde123";
char[] charArray = s.ToCharArray();
string str = "abcde123";
char[] charArray = s.ToCharArray();
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Honestly, I don't quite like your solution. One problem I can see is in the last statement:
CharMap[i] = saTemp[i].Split(' ');
In your file
123
456
789
Digits are NOT separated with spaces - so it won't work.
So the solution does not satisfy your requirements.
I can suggest another solution. It's not shorter really:
CharMap[i] = saTemp[i].Split(' ');
In your file
123
456
789
Digits are NOT separated with spaces - so it won't work.
So the solution does not satisfy your requirements.
I can suggest another solution. It's not shorter really:
private void button1_Click(object sender, EventArgs e)
{
string[][] CharMap;
List<string> lines = new List<string>();
using (StreamReader sr = new StreamReader("text.txt"))
{
String line;
// Read and display lines from the file until the end of the file is reached.
while ((line = sr.ReadLine()) != null)
{
lines.Add(line);
}
}
CharMap = new String[lines.Count][];
for (int firstIndex = 0; firstIndex < lines.Count; firstIndex++)
{
CharMap[firstIndex] = new string[lines[firstIndex].Length];
for (int secondIndex = 0; secondIndex < lines[firstIndex].Length; secondIndex++)
{
CharMap[firstIndex][secondIndex] = lines[firstIndex].Substring(secondIndex, 1);
}
}
// display result in output window
for (int firstIndex = 0; firstIndex < CharMap.Length; firstIndex++)
{
for (int secondIndex = 0; secondIndex < CharMap[firstIndex].Length; secondIndex++)
{
System.Diagnostics.Debug.Write(CharMap[firstIndex][secondIndex]);
}
System.Diagnostics.Debug.WriteLine("");
}
}
If you still have an issue please elaborate.