Skip to content

Instantly share code, notes, and snippets.

@sonnemaf
Created March 15, 2024 12:27
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 sonnemaf/d491976889c93c82fd7db0e146ab1424 to your computer and use it in GitHub Desktop.
Save sonnemaf/d491976889c93c82fd7db0e146ab1424 to your computer and use it in GitHub Desktop.
ScopedDemo
Foo("123,456,7890");
Console.WriteLine();
Bar("123,456,7890");
static void Foo(ReadOnlySpan<char> span) {
Console.WriteLine(span.SplitNext(',').ToString()); // 123
Console.WriteLine(span.SplitNext(',').ToString()); // 456
Console.WriteLine(span.SplitNext(',').ToString()); // 7890
}
static void Bar(ReadOnlySpan<char> span) {
ReadOnlySpan<char> word;
while (!(word = span.SplitNext(',')).IsEmpty) {
Console.WriteLine(word.Length);
Console.WriteLine(word.ToString());
}
}
public static class Extensions {
//public static ReadOnlySpan<T> SplitNext<T>(this ref ReadOnlySpan<T> span, T seperator) where T : IEquatable<T> {
public static ReadOnlySpan<T> SplitNext<T>(this scoped ref ReadOnlySpan<T> span, T seperator) where T : IEquatable<T> {
int pos = span.IndexOf(seperator);
if (pos > -1) {
var part = span.Slice(0, pos);
span = span.Slice(pos + 1);
return part;
} else {
var part = span;
span = span.Slice(span.Length);
return part;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment