Basically I have an array of strings. In this array, a range separator word might exist. For this example, I'm going to use the word to
as range separator. We can assume that the range separator is not the first or last entry in the array. If we find the range separator we need to get the entry before and the entry after the separator, compare the two entries that we can assume are safe to parse as integer
and find the character that differs between them. We then need to create new entries by counting up the number that is different, and return an IEnumerable<string>
containing the new entries. We can also assume that only one character will differ between the start of the range and the end of the range.
For example, if the array contains these values:
1102
to
1602
we need to return
1202
1302
1402
1502
And here's my code:
public static IEnumerable<string> GetRangeSegments(string[] segments, string rangeIndicator)
{
var rangeIndicatorIndex = Array.IndexOf(segments, rangeIndicator);
var rangeSegments = new string[] { };
if (rangeIndicatorIndex < 0)
{
return rangeSegments;
}
var rangeStart = segments[rangeIndicatorIndex - 1];
var rangeEnd = segments[rangeIndicatorIndex + 1];
var startChars = rangeStart.ToCharArray();
var endChars = rangeEnd.ToCharArray();
if (startChars.Length != endChars.Length)
{
return rangeSegments;
}
var diffIndex = -1;
for (var i = 0; i < startChars.Length; i++)
{
if (startChars[i] == endChars[i])
{
continue;
}
diffIndex = i;
break;
}
if (diffIndex == -1)
{
return rangeSegments;
}
var start = int.Parse(startChars[diffIndex].ToString()) + 1;
var end = int.Parse(endChars[diffIndex].ToString());
var numbers = Enumerable.Range(start, end - start);
return rangeSegments.Concat(numbers.Select(number => rangeStart.Remove(diffIndex, 1).Insert(diffIndex, number.ToString())));
}