Venkata Krishna
Venkata Krishna

Reputation: 15122

C# - Stream Reader or whats the best way to do it?

I have a text file with something like this in it.

Tom 1 2
Jerry 3 4

using C#, I have populate this into two arrays

1st array = {Tom,Jerry} - 1 dim array
2nd array ={(1,2),(3,4)} - 2 dim array

Please help me with this. Any help would be appreciated.

Console.WriteLine("Enter the file name with extension:");   
string filename = Console.ReadLine();   
string s = System.IO.File.ReadAllText("C:/Desktop/" + filename);  
Console.WriteLine("\n Text Details in the file: \n \n"+s);

Upvotes: 0

Views: 1067

Answers (4)

jrwren
jrwren

Reputation: 17938

I like a functional approach.

// var fileContent = System.IO.File.ReadAllText("somefilethathasthestuff");
var fileContent = @"Tom 1 2
Jerry 3 4";
var readData = fileContent.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
   .Aggregate(new { names = new List<string>(), data = new List<int[]>() },
       (result, line) => {
           var fields = line.Split(new []{' '}, 2);
           result.names.Add(fields[0]);
           result.data.Add(fields[1].Split(new[] { ' ' }).Select(n => int.Parse(n)).ToArray());
           return result;
        }
   );
string[] firstarray = readData.names.ToArray();
int[][] secondarray = readData.data.ToArray();

This uses a jagged array for the numbers, but you can copy it to a 2d if that is what you really need. Better yet, don't copy to arrays at all. Use List < string> for names and List < int[] > for the numbers.

Upvotes: 0

Giovanni Galbo
Giovanni Galbo

Reputation: 13091

I guess this is a follow up to the last question :)

More hw hints:

As I said in my last answer, splitting on tab (assuming each item is delimited by tab, which looks to be the case) will give you a 1D array of every item in a line (if you use ReadLine).

Item 1 in the ReadLine() array will be the name. Put that into your 1D names array. Items 2 to N of ReadLine() array will be the test scores. Put that into your 2D scores array.

The first dimension of the scores array will be the student index. The second dimension will be the score array.

That may sound confusing, but if you think about it, a 2D array is an array of arrays.

So even though your data file doesn't show the student index, it's implied:

0 Joe 100 80 77
1 Bob 65 93 100

Names array will look like:

[0] Joe
[1] Bob

and scores array will look like:

[0][0] 100
[0][1] 80
[0][2] 77
[1][0] 65
[1][1] 93
[1][2] 100

Notice that the index (first dimension) in the scores array coincide with the index of the names array.

Upvotes: 1

Jess
Jess

Reputation: 8700

A more complete version ;)

        string filename = "";
        do
        {
            Console.WriteLine("Enter the file name with extension:");
            filename = Environment.GetEnvironmentVariable("HOMEDRIVE") + Environment.GetEnvironmentVariable("HOMEPATH") + "\\Desktop\\" + Console.ReadLine();
            if (!System.IO.File.Exists(filename))
                Console.WriteLine("File doesn't exist!");
            else
                break;
        } while (true);
        System.IO.StreamReader readfile = new System.IO.StreamReader(filename);

        List<string> Names = new List<string>();
        List<int[]> Numbers = new List<int[]>();
        string val = "";
        while ((val = readfile.ReadLine()) != null)
        {
            if (val == string.Empty)
                continue;
            List<string> parts = val.Split(' ').ToList<string>();
            Names.Add(parts[0]);
            parts.RemoveAt(0);
            Numbers.Add(parts.ConvertAll<int>(delegate(string i) { return int.Parse(i); }).ToArray());
        }
        readfile.Close();

        //Print out info
        foreach (string name in Names)
        {
            Console.Write(name + ", ");
        }
        Console.WriteLine();
        foreach (int[] Numberset in Numbers)
        {
            Console.Write("{");
            foreach (int number in Numberset)
                Console.Write(number + ", ");
            Console.Write("} ");
        }
        Console.ReadLine();

Upvotes: 0

Dawid Kowalski
Dawid Kowalski

Reputation: 1257

There are few ways, it depends how "elegant" you want to be, and / or whether Tom, Jerry is always going to be one word.

  • Parse every line with String methods
  • Parse every line with RegEx
  • Use Linq to Text

Simplest way would be something like this (quick and dirty, very fragile solution):

var path = "fileName.txt";

var names = new List<string>();
var values = new List<KeyValuePair<int, int>>();

using (var reader = File.OpenText(path))
{
        string s = "";
        while ((s = reader.ReadLine()) != null)
        {
            String[] arr = s.Split(' ');
            names.Add(arr[0]);
            values.Add(new KeyValuePair<int, int>(int.Parse(arr[1]), int.Parse(arr[2])));
        }
}

If you need you can convert lists to array

Upvotes: 1

Related Questions