CSharp · Script
using System;
public int ClosestIndexOf(string input, char value, int startIndex)
{
if (startIndex > input.Length)
throw new IndexOutOfRangeException("Start index was outside the length of input string.");
// get closest index below and above specified "startIndex" position
int below = input.LastIndexOf(value, startIndex - 1);
int above = input.IndexOf(value, startIndex);
var mid = (below + above) / 2;
int result;
if (mid > startIndex)
result = below;
else
result = above;
Console.WriteLine(string.Format("StartIndex: {0}, Below: {1}, Above: {2}, Mid: {3}, Result: {4}", startIndex, below, above, mid, result));
return result;
}
string test = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
Console.WriteLine("0 1 2 3 4 5 ");
Console.WriteLine("01234567890123456789012345678901234567890123456789012345");
Console.WriteLine("————————————————————————————————————————————————————————");
Console.WriteLine(test);
Console.WriteLine("————————————————————————————————————————————————————————");
ClosestIndexOf(test, ' ', 30); // 27
ClosestIndexOf(test, ' ', 35); // 39
ClosestIndexOf(test, ' ', 50); // 50
ClosestIndexOf(test, ' ', 19); // 17 & 21 have same offset, return 21
ClosestIndexOf(test, 'x', 30); // -1
ClosestIndexOf(test, 'a', 45); // 40
ClosestIndexOf(test, 'a', 20); // 22
ClosestIndexOf(test, ' ', 60); // IndexOutOfRangeException