【问题标题】:Finding index of a string through coordinates通过坐标查找字符串的索引
【发布时间】:2021-11-01 02:32:02
【问题描述】:

我正在为 Windows 控制台项目开发一个屏幕,并且一直在努力解决以下问题。

场景:

  • 我在控制台打印了一个字符串(可以在任何起始位置打印)
  • 我有变量存储字符串开始的坐标 (x,y)
  • 我有打印字符串的长度。

我试图猜测光标在字符串的哪个位置。

例子:

  • 字符串从位置 (Console.CursorLeft, Console.CursorTop) 开始,比如说 (30,14)
  • 每行的最大 X 为 Console.WindowWidth,假设为 50。
  • 字符串长度为 250 个字符,这意味着字符串在位置 (30,19) 结束

如果我将光标移动到随机位置 (3,16),我希望能够计算字符串的相应索引/位置。

我尝试了不同的公式,欧几里得距离在这里不起作用,因为字符串逐行排列。 这个功能我已经从零开始了好几次了,现在我需要重新从0开始。

如果有人能就我应该使用的公式给我建议,我将不胜感激

public static int GetStringIndex(int startX, int startY, string text)
        {
            int index = -1;
            int currentX = Console.CursorLeft;
            int currentY = Console.CursorTop;


            return index;
        }

【问题讨论】:

    标签: c# string console coordinates


    【解决方案1】:

    如果我理解正确,这就是你想要的:

    int current = currentX + currentY * Console.BufferWidth;
    int start = startX + startY * Console.BufferWidth;
    
    return start <= current && current < start + text.Length ? current - start : -1;
    

    当您将控制台视为一个大的一维数组时,这很容易。

    【讨论】:

    • 我很好奇,是否有可能再次从索引反转到坐标?
    • @LordCaos,这是可能的。 x = screenIndex % Console.BufferWidth; y = screenIndex / Console.BufferWidth;
    猜你喜欢
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 2023-04-10
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多