Is there a means to get the index of the first non-whitespace character in a string (or more generally, the index of the first character matching a condition) in C# without
var match = Regex.Match(" \t test ", @"\S"); // \S means all characters that are not whitespace
if (match.Success)
{
int index = match.Index;
//do something with index
}
else
{
//there were no non-whitespace characters, handle appropriately
}
If you'll be doing this often, for performance reasons you should cache the compiled Regex for this pattern, e.g.:
static readonly Regex nonWhitespace = new Regex(@"\S");
Then use it like:
nonWhitespace.Match(" \t test ");