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
Since there were several solutions here I decided to do some performance tests to see how each performs. Decided to share these results for those interested...
int iterations = 1000000;
int result = 0;
string s= " \t Test";
System.Diagnostics.Stopwatch watch = new Stopwatch();
// Convert to char array and use FindIndex
watch.Start();
for (int i = 0; i < iterations; i++)
result = Array.FindIndex(s.ToCharArray(), x => !char.IsWhiteSpace(x));
watch.Stop();
Console.WriteLine("Convert to char array and use FindIndex: " + watch.ElapsedMilliseconds);
// Trim spaces and get index of first character
watch.Restart();
for (int i = 0; i < iterations; i++)
result = s.IndexOf(s.TrimStart().Substring(0,1));
watch.Stop();
Console.WriteLine("Trim spaces and get index of first character: " + watch.ElapsedMilliseconds);
// Use extension method
watch.Restart();
for (int i = 0; i < iterations; i++)
result = s.IndexOf(c => !char.IsWhiteSpace(c));
watch.Stop();
Console.WriteLine("Use extension method: " + watch.ElapsedMilliseconds);
// Loop
watch.Restart();
for (int i = 0; i < iterations; i++)
{
result = 0;
foreach (char c in s)
{
if (!char.IsWhiteSpace(c))
break;
result++;
}
}
watch.Stop();
Console.WriteLine("Loop: " + watch.ElapsedMilliseconds);
Results are in milliseconds....
Where s = " \t Test"
Convert to char array and use FindIndex: 154
Trim spaces and get index of first character: 189
Use extension method: 234
Loop: 146
Where s = "Test"
Convert to char array and use FindIndex: 39
Trim spaces and get index of first character: 155
Use extension method: 57
Loop: 15
Where s = (1000 character string with no spaces)
Convert to char array and use FindIndex: 506
Trim spaces and get index of first character: 534
Use extension method: 51
Loop: 15
Where s = (1000 character string that starts with " \t Test")
Convert to char array and use FindIndex: 609
Trim spaces and get index of first character: 1103
Use extension method: 226
Loop: 146
Draw your own conclusions but my conclusion is to use whichever one you like best because the performance differences is insignificant in real world scenerios.