如何改进此控制台应用程序?

问题描述 投票:-1回答:1

我试图突出显示文件中的特定单词,并使用突出显示的单词显示控制台中的所有文本。

我试图使用正则表达式对其进行优化,但在尝试将红色显示为所显示的每个句子中的所需匹配时会卡住。所以我结束了使用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();
c# performance optimization console console-application
1个回答
0
投票

这是一个使用正则表达式的命题:

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

但是,我担心有关子串重复的表现......

© www.soinside.com 2019 - 2024. All rights reserved.