String[] digits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
String line = "four95qvkvveight5";
index_digit2 = digits
.Where(d => line.Contains(d))
.Max(d => line.IndexOf(d));
I am iterating over a file searching for the first and the last digit in each line. This is what I'm using to search for the last integer in each line, which is working fine until I reach the string you see above. Because i'm getting the index of the first 5, not the last. (index_digit2 = 5 not like I'm expecting 16)
I'm confused why it is like that and if there is a quick fix.
In all other cases this works pretty fine, as far as I could check.
I'd just iterate the characters in your string from back to start:
int? index = null;
for(int i = myString.Length - 1; i >= 0; i--)
{
if(myString[i].IsDigit())
{
index = i;
break;
}
}
or a bit shorter:
var result = myString.Select((x, i) => new { Index = i, Char = x }).LastOrDefault(x => x.Char.IsDigit())?.Index;
or using string.LastIndexOfAny
:
var result = myString.LastIndexOfAny(digits);