【问题标题】:How can I improve this Console Application?如何改进此控制台应用程序?
【发布时间】:2019-04-23 14:07:48
【问题描述】:

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

我曾尝试使用正则表达式对其进行优化,但在尝试将出现的每个句子中所需的匹配项涂成红色时却卡住了。所以我结束了使用 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();

【问题讨论】:

  • Console.Write() 是一项昂贵的操作。如果您需要提高性能,一种选择是尽可能少地使用它。使用 StringBuilder 构建字符串文本(在这种情况下避免使用连接或字符串插值),直到找到预期的单词(需要突出显示的单词),一旦找到需要突出显示的单词,只需对其进行控制台。在每次迭代中避免使用 Console.Write()

标签: c# performance optimization console console-application


【解决方案1】:

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

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

但是,我担心子字符串重复的性能......

【讨论】:

    猜你喜欢
    • 2013-02-20
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    • 2013-02-11
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多