-1

I am trying to highlight an specific word from a file and show all the text in the console with the highlighted word.

I have tried to optimize it with Regular Expressions but got stuck when trying to color red just the desired match in each sentence it appears. So I ended using the For Loop alternative instead.

Is there a better way to do this?

        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();
Gdl
  • 11
  • 2
  • Possible duplicate of [Find text in string with C#](https://stackoverflow.com/questions/10709821/find-text-in-string-with-c-sharp) – Kevin Apr 23 '19 at 14:21
  • Console.Write() is an expensive operation. if you need performance improvement one option is to use it as less as possible. Build the string text using a StringBuilder(avoid using Concatenation or string interpolation in this case ) till you find the expected word(word need to be highlighted), once you find the word which needs to be highlighted, just Console it. Avoid Console.Write() in each iteration – Shyam Kumar Apr 23 '19 at 14:26

1 Answers1

0

Here is a proposition using 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();
    }

However, I'm afraid about performance about Substring repetition...

KiwiJaune
  • 530
  • 2
  • 16