Abdullah Khan Abdullah Khan - 2 months ago 7
C# Question

How to read a comma position from an Array C#

Hi I'm Trying o make an atom simulation game where I can read my data from a txt file and use the data for the simulation/game. I have read the file but I am having trouble finding the commaposition from the string array. The txt file looks like this: 1,H,Hydrogen,1,1+
3,Li,Lithium,7,1+

static void Main(string[] args)
{

string commapostition;

string[] list = new string[44];

StreamReader rFile = new StreamReader(@"JUNK1.txt");
for (int i = 0; i < 44; i++)
{
list[i] = rFile.ReadLine();
}
rFile.Close();

for (int i = 0; i < 44; i++)
{
commapostition = list[i].IndexOf(',');
}
}
}


}

Answer

If each line of your file looks like what you posted:

1,H,Hydrogen,1,1+

And the order Atomic #, Symbol, Name, Mass, Charge is constant, you can do something like this:

static void Main(string[] args)
{
    string filename = @"JUNK1.txt";
    string[] lines = File.ReadAllLines(fileName);

    for (int i = 0; i < lines.Length; i++)
    {
        string[] entries = lines[i].Split(',');

        string atomicNumber = entries[0];
        string symbol = entries[1];
        string name = entries[2];
        string mass = entries[3];
        string charge = entries[4];

        // Do stuff with these values...
    }
}