user3660143
user3660143

Reputation: 1

How to read int[] from a text file in C#?

I have a text file "read.txt" like this

a 1 2 3 4
b 4 6 7 8
c 5 6 7 1
...

In C# I'd like to define:

int[] a = {1,2,3,4};
int[] b = {4, 6, 7, 8};
int[] c= {5, 6, 7, 1};
...

I'd like to ask how to read all lines and put into c# file like above

Thank you.

Upvotes: 0

Views: 925

Answers (2)

Søren Ullidtz
Søren Ullidtz

Reputation: 1514

I'm not sure what the exact goal is, but my guess is you need something like this:

public Dictionary<string, int[]> GetArraysFromFile(string path)
{
    Dictionary<string, int[]> arrays = new Dictionary<string, int[]>();
    string[] lines = System.IO.File.ReadAllLines(path);
    foreach(var line in lines)
    {
        string[] splitLine = line.Split(' ');
        List<int> integers = new List<int>();
        foreach(string part in splitLine)
        {
            int result;
            if(int.TryParse(part, out result))
            {
                integers.Add(result);
            }
        }
        if(integers.Count() > 0)
        {
            arrays.Add(splitLine[0], integers.ToArray());
        }
    }

    return arrays;
}

This assumes that your first char is the letter/key. You will have a dictionary where your letter is the key and the value is the array.

Upvotes: 1

Peter Ittner
Peter Ittner

Reputation: 551

You can use the following Methods to solve your task:

System.IO.File.ReadAllLines   // Read all lines into an string[]
string.Split                  // Call Split() on every string and split by (white)space
Int32.TryParse                // Converts an string-character to an int

To Create an array of ints I would create first a List<int> and Add() every parsed integer in it. Than you can call ToArray() upon the list to get your array.

Upvotes: 1

Related Questions