c# - 通过坐标查找字符串的索引
问题描述
我正在为 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;
}
解决方案
如果我理解正确,这就是你想要的:
int current = currentX + currentY * Console.BufferWidth;
int start = startX + startY * Console.BufferWidth;
return start <= current && current < start + text.Length ? current - start : -1;
当您将控制台视为一个大的一维数组时,这很容易。
推荐阅读
- javascript - 当需要数组时,Filter() 方法返回布尔值
- flutter - Flutter - 右溢出
- python - 无法使用 Miniconda 将 Python 从 3.4.5 升级到 3.6。遇到 UnsatisfiableError
- postgresql - 从具有私有和公共 IP 的虚拟机连接到私有 IP 上的 Google Cloud SQL 实例失败
- excel - Excel 根据下拉菜单跳转到特定列/单元格
- python - 熊猫数据框放大
- django - ManyToManyRelation 中的 Django models.CASCADE
- python - Python:字符串连接
- compiler-construction - 我怎样才能使它能够用 LALR(1) 解决
- r - 为什么 XPath 中的“link”比“//link”快?