c# - ClosestIndexOf 的最简单实现

标签 c# optimization conditional-statements

我想编写一个 C# 字符串扩展方法 ClosestIndexOf(char, index) ,它会在提供的索引周围为我提供字符串中某个字符的最接近索引。

让我们用我的输入字符串检查一些例子:

0         1         2         3         4         5    
01234567890123456789012345678901234567890123456789012345
--------------------------------------------------------
Lorem ipsum dolor sit amet, consectetur adipiscing elit.

输入字符串长度为 56(我添加了以 0 开头的索引位置。

示例结果调用:

input.ClosestIndexOf(' ', 30); // 27
input.ClosestIndexOf(' ', 35); // 39
input.ClosestIndexOf(' ', 50); // 50
input.ClosestIndexOf(' ', 19); // 17 & 21 have same offset, return 21
input.ClosestIndexOf(' ', 60); // OutOfRangeException
input.ClosestIndexOf('x', 30); // -1

到目前为止我已经写了这个,但它需要更多的测试,而且它也很丑陋并且条件太多。

// index is out of range
if (index > value.Length)
    throw new ArgumentOutOfRangeException();

// get closest index below and above specified "index" position
int below = result.LastIndexOf('-', index - 1);
int above = result.IndexOf('-', index);

// followed by conditions

我希望这个问题或多或少是一个数学问题/表达式,这样我就可以避免条件并使其更简单。

This is initial code 供您继续使用。正如您从结果中看到的那样,当在下方和上方 找到特定字符或两者都不存在时,我的初始代码有效。但如果每个条件的值为 -1,我将不得不引入其他条件。我没有添加这些,因为这正是我要优化的。

您将对初始代码进行哪些优化以使其更短、性能更好且条件更少?

最佳答案

获取您的搜索字符的所有出现以及这次出现的 found_index

计算 search_indexfound_index 之间的距离。

  d = abs(s - f);

保持距离最小。

关于c# - ClosestIndexOf 的最简单实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29388866/

相关文章:

c# - 类型 c# 上的开关大小写

node.js - gulp 中的条件语句

mysql - SQL 条件插入或更新语句取决于一对列。使用唯一索引?

c# - 具有包罗万象的路由的 ASP.NET Web API PUT

c# - 在 C# 中将命令发送到 CMD

mysql - SUM(val/2) 和 SUM(val)/2 哪个更好?

arrays - 缓存友好的二维数组的元素排序

C++ switch 语句评估

c# - ASP .NET - 使用 asp :CheckBox in ListView

c# - 如何在 C# 中按以...开头的属性选择节点