Fastest way to find strings in a file

后端 未结 5 1287
耶瑟儿~
耶瑟儿~ 2021-01-18 23:04

I have a log file that is not more than 10KB (File size can go up to 2 MB max) and I want to find if atleast one group of these strings occurs in the files. These strings w

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-18 23:33

    I would read it line by line and check the conditions. Once you have seen a group you can quit. This way you don't need to read the whole file into memory. Like this:

        public bool ContainsGroup(string file)
        {
            using (var reader = new StreamReader(file))
            {
                var hasAction = false;
                var hasInput = false;
                var hasResult = false;
                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();
                    if (!hasAction)
                    {
                        if (line.StartsWith("ACTION:"))
                            hasAction = true;
                    }
                    else if (!hasInput)
                    {
                        if (line.StartsWith("INPUT:"))
                            hasInput = true;
                    }
                    else if (!hasResult)
                    {
                        if (line.StartsWith("RESULT:"))
                            hasResult = true;
                    }
    
                    if (hasAction && hasInput && hasResult)
                        return true;
                }
                return false;
            }
        }
    

    This code checks if there is a line starting with ACTION then one with INPUT and then one with RESULT. If the order of those is not important then you can omit the if () else if () checks. In case the line does not start with the strings replace StartsWith with Contains.

提交回复
热议问题