Last active
December 3, 2021 08:53
-
-
Save MiddleTommy/5a571dd3787837c6a83a30806907979f to your computer and use it in GitHub Desktop.
Get Count Occurrences of substring in string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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