首页 > 解决方案 > 通过坐标查找字符串的索引

问题描述

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

设想:

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

例子:

如果我将光标移动到随机位置 (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#stringconsolecoordinates

解决方案


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

int current = currentX + currentY * Console.BufferWidth;
int start = startX + startY * Console.BufferWidth;

return start <= current && current < start + text.Length ? current - start : -1;

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


推荐阅读