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
You can use the String.IndexOfAny function which returns the first occurrence any character in a specified array of Unicode characters.
Alternatively, you can use the String.TrimStart function which remove all white space characters from the beginning of the string. The index of the first non-white space character is the difference between the length of the original string and the trimmed one.
You can even pick a set of characters to trim :)
Basically, if you are looking for a limited set of chars (let's say digits) you should go with the first method.
If you are trying to ignore a limited set of characters (like white spaces) you should go with the second method.
A Last method would be to use the Linq methods:
string s = " qsdmlkqmlsdkm";
Console.WriteLine(s.TrimStart());
Console.WriteLine(s.Length - s.TrimStart().Length);
Console.WriteLine(s.FirstOrDefault(c => !Char.IsWhiteSpace(c)));
Console.WriteLine(s.IndexOf(s.FirstOrDefault(c => !Char.IsWhiteSpace(c))));
Output:
qsdmlkqmlsdkm
8
q
8