Как я могу улучшить это консольное приложение? - PullRequest
0 голосов
/ 23 апреля 2019

Я пытаюсь выделить определенное слово из файла и показать весь текст в консоли с выделенным словом.

Я пытался оптимизировать его с помощью регулярных выражений, но застрял при попытке закрасить краснымпросто искомое совпадение в каждом предложении.Поэтому я перестал использовать альтернативу For Loop.

Есть ли лучший способ сделать это?

        StreamReader sr = new StreamReader("TestFile.txt");



        string text = sr.ReadToEnd();
        var word = text.Split(" ");
        for (int i = 0; i < word.Length; i++)
        {
            if (word[i].Contains("World", StringComparison.CurrentCultureIgnoreCase))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write(word[i] + " ");
                Console.ResetColor();
            }
            else
            {
                Console.Write(word[i] + " ");
            }

        }
        Console.ReadLine();

1 Ответ

0 голосов
/ 23 апреля 2019

Вот предложение с использованием Regex:

    static void Main(string[] args)
    {
        StreamReader sr = new StreamReader("TestFile.txt");

        String searched = "World";
        Regex reg = new Regex(@"\b\w*" + searched + @"\w*\b");

        string text = sr.ReadToEnd();
        int lastIndex = 0;

        MatchCollection matches = reg.Matches(text);

        foreach(Match m in matches)
        {
            Console.Write(text.Substring(lastIndex, m.Index - lastIndex));
            Console.ForegroundColor = ConsoleColor.Red;
            Console.Write(m.Value);
            Console.ResetColor();

            lastIndex = m.Index + m.Length;
        }

        if(lastIndex < text.Length)
            Console.Write(text.Substring(lastIndex, text.Length - lastIndex));

        Console.ReadLine();
    }

Тем не менее, я боюсь производительности по поводу повторения подстроки ...

...