简体   繁体   中英

FileStream Class C# Input from txt file to array

I am trying to make use of StreamReader and taking data from text files and store it into an array. I am having an issue where I think the fix is simple, but I am stumped. When I print the array, it prints every single token in the txt file instead of the single line of data containing the search name along with the 11 int tokens. 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;
    }
}

That sure is a lot of code, this snippet does not account for duplicates but if you were willing to work with linq, something like this might help? You could also just iterate over the file_text array using a for-loop and perhaps set your return array in that. Anyway a lot less code to mess with

    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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM