我试图利用StreamReader并从文本文件中获取数据并将其存储到数组中。我遇到的问题是我认为解决方法很简单,但是我很沮丧。当我打印数组时,它将打印txt文件中的每个单个标记,而不是包含搜索名称以及11个int标记的单行数据。 Long_Name.txtsample
public class SSA
{
public void Search()
{
Console.WriteLine("Name to search for?");
string n = Console.ReadLine();
Search(n, "Files/Names_Long.txt");
}
public int[] Search(string targetName, string fileName)
{
int[] nums = new int[11];
char[] delimiters = { ' ', '\n', '\t', '\r' };
using (TextReader sample2 = new StreamReader("Files/Exercise_Files/SSA_Names_Long.txt"))
{
string searchName = sample2.ReadLine();
if (searchName.Contains(targetName))
{
Console.WriteLine("Found {0}!", targetName);
Console.WriteLine("Year\tRank");
}
else
Console.WriteLine("{0} was not found!", targetName);
while (searchName != null)
{
string[] tokensFromLine = searchName.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
int arrayIndex = 0;
int year = 1900;
foreach (string token in tokensFromLine)
{
int arrval;
if (int.TryParse(token, out arrval))
{
nums[arrayIndex] = arrval;
year += 10;
Console.WriteLine("{0}\t{1}", year, arrval);
arrayIndex++;
}
}
searchName = sample2.ReadLine();
}
}
return nums;
}
}
答案 0 :(得分:0)
那肯定有很多代码,此代码段不包含重复项,但是如果您愿意使用linq,类似的内容可能会有所帮助?您也可以使用for循环遍历file_text数组,并在其中设置返回数组。无论如何,要处理的代码要少得多
public int[] Search(string targetName, string fileName)
{
List<string> file_text = File.ReadAllLines("Files/Exercise_Files/SSA_Names_Long.txt").ToList();
List<string> matching_lines = file_text.Where(w => w == targetName).ToList();
List<int> nums = new List<int>();
foreach (string test_line in matching_lines)
{
nums.Add(file_text.IndexOf(test_line));
}
return nums.ToArray();
}