【问题标题】:Is there a way to programmatically point the cursor at a specific word?有没有办法以编程方式将光标指向特定单词?
【发布时间】:2019-05-21 21:33:28
【问题描述】:

我目前有一个控制台应用程序,我正在通过命令行使用一个文件。给定的文件现在变成一个巨大的字符串。这个字符串被分成一个单词数组。 这个数组是用 foreach 搜索我的搜索词的。我现在的问题是如何解决将焦点直接放在找到的第一个单词并选择该单词的问题。

var splittedTxt = text.Split(' ');

        if (decisionForWholeWords == true && decisionForSpelling == false)
        {
            foreach (var item in splittedTxt)
            {
                if (wordToFind.ToLower() == item.ToLower())
                {
                    Console.BackgroundColor = ConsoleColor.Red;

                    wordFound = true;
                }
                Console.Write(item);
                if (wordFound) // reset color
                {
                    Console.BackgroundColor = ConsoleColor.Black;

                    wordFound = false;
                }
                Console.Write(" ");
            }
        }

【问题讨论】:

    标签: c# console


    【解决方案1】:

    你可以用一个方法来设置光标:

    Console.SetCursorPosition(x, y);
    

    或者通过使用 left 和 top 属性:

    Console.CursorLeft = x;
    Console.CursorTop = y;
    

    您必须弄清楚单词的位置并将光标设置到该位置。

    【讨论】:

    • 问题是我将文本拆分为一个数组,现在每个单词都单独包含在其中。我现在应该如何找出位置,理论上我只有数组中总是有一个单词?
    • 这取决于你如何显示文字;如果您在新行上打印每个单词,则可以使用 for 循环而不是 foreach 循环。您的单词所在的索引将是您的光标所在的高度。
    【解决方案2】:
    if (decisionForWholeWords == true && decisionForSpelling == false)
    {
            int index = 0;
            foreach (var item in splittedTxt)
            {
                //do what you want the index.
                if (wordToFind.ToLower() == item.ToLower())
                {
                    Console.BackgroundColor = ConsoleColor.Red;
    
                    wordFound = true;
                }
                Console.Write(item);
                if (wordFound) // reset color
                {
                    Console.BackgroundColor = ConsoleColor.Black;
    
                    wordFound = false;
                }
                Console.Write(" ");
    
                index += item.Length;
                index += 1; //for the space
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-09
      • 2016-02-26
      • 2013-04-02
      • 2021-08-28
      相关资源
      最近更新 更多