Skip to content

Count substring occurrences in a string #73441

Answered by EgorBo
LeaFrock asked this question in Show and tell
Discussion options

You must be logged in to vote

Culture-aware IndexOf is slow by definition, it uses ICU under the hood. If it works for you consider setting Ordinal mode, e.g.:

public int IndexOf_Count()
{
    int count = 0;
    int index = Source.IndexOf(Value, StringComparison.Ordinal);
    while (index >= 0)
    {
        count++;
        index = Source.IndexOf(Value, index + Value.Length, StringComparison.Ordinal);
    }
    return count;
}

However, for the best performance you need .NET 7.0 where we introduced a new algorithm for IndexOf for substrings - #63285

.NET 6.0 CurrentCulture (ICU)

|        Method |     Mean |
|-------------- |---------:|
| IndexOf_Count | 358.8 ns |

.NET 6.0 Ordinal

|        Method |     Mean |
|----…

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@LeaFrock
Comment options

Answer selected by LeaFrock
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants