Skip to content

Instantly share code, notes, and snippets.

@MiddleTommy
Last active December 3, 2021 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MiddleTommy/5a571dd3787837c6a83a30806907979f to your computer and use it in GitHub Desktop.
Save MiddleTommy/5a571dd3787837c6a83a30806907979f to your computer and use it in GitHub Desktop.
Get Count Occurrences of substring in string
/// <summary>
/// Gets the count of substrings in the string
/// </summary>
/// <param name="text"></param>
/// <param name="substring"></param>
/// <returns></returns>
public static int GetCount(this string text, string substring)
{
int count = 0;
var span = text.AsSpan();
var len = substring.Length;
for (int i = 0; i <= span.Length - len; i++)
{
var slice = span.Slice(i, len);
if (slice.Equals(substring, StringComparison.Ordinal))
count++;
}
return count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment