首先让我首先感谢大家加入本网站,我已经从中获得了很多有用的信息.包括一些基本的文本文件解析到数组,但我现在想更进一步.
我有一个看起来像这样的文本文件
Start Section 1 - foods
apple
bannana
pear
pineapple
orange
end section 1
Start section 2 - animals
dog
cat
horse
cow
end section 2
Run Code Online (Sandbox Code Playgroud)
我想要做的是使用文件的单个读取将第1部分中的数据复制到名为"foods"的数组中,将第2部分复制到名为"animals"的数组中
现在我可以通过为每个部分使用一个新循环,每次关闭并重新打开文件,循环直到找到我想要的部分并创建数组来使其工作.
但我当时认为必须有一种方法可以一次性将每个部分读入一个单独的数组中.
所以我目前的代码是
List<string> typel = new List<string>();
using (StreamReader reader = new StreamReader("types.txt")) // opens file using streamreader
{
string line; // reads line by line in to varible "line"
while ((line = reader.ReadLine()) != null) // loops untill it reaches an empty line
{
typel.Add(line); // adds the line to the list varible "typel"
}
}
Console.WriteLine(typel[1]); // test to see if list is beeing incremented
string[] type = typel.ToArray(); //converts the list to a true array
Console.WriteLine(type.Length); // returns the number of elements of the array created.
Run Code Online (Sandbox Code Playgroud)
这是一个简单的文本文件,没有任何部分只是值列表,使用列表似乎是处理未知长度的数组的好方法.
我也想知道如何处理第一个值.
例如,如果我这样做
while ((line = reader.ReadLine()) != Start Section 1 - foods)
{
}
while ((line = reader.ReadLine()) != end Section 1)
{
foods.Add(line);
}
...
....
Run Code Online (Sandbox Code Playgroud)
我最终将"开始第1节 - 食物"作为阵列元素之一.我可以用代码删除它,但是有一种简单的方法可以避免这种情况,所以只填充列表项吗?
干杯再次感谢所有的帮助.很多年后重新开始编程很棒.
亚伦
阅读台词不是问题,请参阅System.IO.ReadAllLines(fileName)及其兄弟姐妹。
您需要的是一个(非常简单的)解释器:
// totally untested
Dictionary<string, List<string>> sections = new Dictionary<string, List<string>>();
List<string> section = null;
foreach(string line in GetLines())
{
if (IsSectionStart(line))
{
string name = GetSectionName(line);
section = new List<string>();
sections.Add(name, section);
}
else if (IsSectionEnd(line))
{
section = null; // invite exception when we're lost
}
else
{
section.Add(line);
}
}
...
List<string> foods = sections ["foods"];
Run Code Online (Sandbox Code Playgroud)
寻找开始和结束的指针。这是你开始将东西放入数组、列表等的地方。
以下是使其变得非常灵活的尝试:
class Program
{
private static Dictionary<string, List<string>> _arrayLists = new Dictionary<string, List<string>>();
static void Main(string[] args)
{
string filePath = "c:\\logs\\arrays.txt";
StreamReader reader = new StreamReader(filePath);
string line;
string category = "";
while (null != (line = reader.ReadLine()))
{
if (line.ToLower().Contains("start"))
{
string[] splitHeader = line.Split("-".ToCharArray());
category = splitHeader[1].Trim();
}
else
{
if (!_arrayLists.ContainsKey(category))
{
List<string> stringList = new List<string>();
_arrayLists.Add(category, stringList);
}
if((!line.ToLower().Contains("end")&&(line.Trim().Length > 0)))
{
_arrayLists[category].Add(line.Trim());
}
}
}
//testing
foreach(var keyValue in _arrayLists)
{
Console.WriteLine("Category: {0}",keyValue.Key);
foreach(var value in keyValue.Value)
{
Console.WriteLine("{0}".PadLeft(5, ' '), value);
}
}
Console.Read();
}
}
Run Code Online (Sandbox Code Playgroud)