Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit 7b56128

Browse files
committed
Implement Span<char>.CountOccurrencesOf()
1 parent 15f6d20 commit 7b56128

File tree

2 files changed

+16
-13
lines changed

2 files changed

+16
-13
lines changed

src/ServiceStack.Text/StringExtensions.cs

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1220,18 +1220,8 @@ public static IEnumerable<string> ReadLines(this string text)
12201220
}
12211221
}
12221222

1223-
public static int CountOccurrencesOf(this string text, char needle)
1224-
{
1225-
var chars = text.ToCharArray();
1226-
var count = 0;
1227-
var length = chars.Length;
1228-
for (var n = length - 1; n >= 0; n--)
1229-
{
1230-
if (chars[n] == needle)
1231-
count++;
1232-
}
1233-
return count;
1234-
}
1223+
public static int CountOccurrencesOf(this string text, char needle) =>
1224+
text.AsSpan().CountOccurrencesOf(needle);
12351225

12361226
public static string NormalizeNewLines(this string text)
12371227
{

src/ServiceStack.Text/StringSpanExtensions.cs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -643,6 +643,19 @@ public static List<string> ToStringList(this IEnumerable<ReadOnlyMemory<char>> f
643643
}
644644
}
645645
return to;
646-
}
646+
}
647+
648+
public static int CountOccurrencesOf(this ReadOnlySpan<char> value, char needle)
649+
{
650+
var count = 0;
651+
var length = value.Length;
652+
for (var n = length - 1; n >= 0; n--)
653+
{
654+
if (value[n] == needle)
655+
count++;
656+
}
657+
return count;
658+
}
659+
647660
}
648661
}

0 commit comments

Comments
 (0)