Get Index of First non-Whitespace Character in C# String

后端 未结 11 1900
执念已碎
执念已碎 2020-12-17 09:27

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

11条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 10:31

    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.

提交回复
热议问题