我想编写一个 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_index
和 found_index
之间的距离。
d = abs(s - f);
保持距离最小。
关于c# - ClosestIndexOf 的最简单实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29388866/