如何从数组中读取逗号位置
本文关键字:位置 读取 数组 | 更新日期: 2023-09-27 18:11:17
嗨,我想做一个原子模拟游戏,我可以从文本文件中读取我的数据,并使用模拟/游戏的数据。我读了文件,但我有困难找到从字符串数组的组合。txt文件看起来像这样:1,H,氢,1,1+3、李锂、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(',');
}
}
如果你的文件的每一行看起来都像你发布的:
1,H,Hydrogen,1,1+
而Atomic #, Symbol, Name, Mass, Charge
的阶是常数,你可以这样做:
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...
}
}
假设您有一个文本文件JUNK1.txt
,其行为:
1,H,Hydrogen,1,1+
3,Li,Lithium,7,1+
你可以这样读这行:
static void Main(string[] args)
{
// Path to the file you want to read in
var filePath = "path/to/JUNK1.txt";
// This will give you back an array of strings for each line of the file
var fileLines = File.ReadAllLines(filePath);
// Loop through each line in the file
foreach (var line in fileLines)
{
// This will give you an array of all the values that were separated by a comma
var valuesSeparatedByCommas = line.Split(',');
// Do whatever with the array valuesSeparatedByCommas
}
}
在第一行执行上述代码后,变量valuesSeparatedByCommas
数组看起来如下所示:
0 1 2 3 4
+---+---+----------+---+----+
| 1 | H | Hydrogen | 1 | 1+ |
+---+---+----------+---+-----
现在你可以根据它的索引访问该行的每一部分:
// valueAtPosition0 will be '1'
var valueAtPosition0 = valuesSeparatedByCommas[0];
// valueAtPosition1 will be 'H'
var valueAtPosition1 = valuesSeparatedByCommas[1];