I need to be able to say something like myString.IndexOf(c => !Char.IsDigit(c)), but I can’t find any such method in the .NET framework. Did I miss something?
The following works, but rolling my own seems a little tedious here:
using System;
class Program
{
static void Main()
{
string text = "555ttt555";
int nonDigitIndex = text.IndexOf(c => !Char.IsDigit(c));
Console.WriteLine(nonDigitIndex);
}
}
static class StringExtensions
{
public static int IndexOf(this string self, Predicate<char> predicate)
{
for (int index = 0; index < self.Length; ++index) {
if (predicate(self[index])) {
return index;
}
}
return -1;
}
}
MSDN will show you all methods and extensions for a given type: MSDN String Class
There is not currently an extension method specifically for
Stringdescribing exactly what you have provided. As others have stated, rolling your own is not a bad choice since other options(besidesare not near as elegant.regex)Edit I was mistaken about the efficiency of using
RegExto find indexes…