Last active
October 17, 2024 13:52
-
-
Save sonnemaf/d491976889c93c82fd7db0e146ab1424 to your computer and use it in GitHub Desktop.
ScopedDemo
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
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()); | |
} | |
//while (!(word = span.SplitNextWithScoped(',')).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> { | |
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; | |
} | |
} | |
public static ReadOnlySpan<T> SplitNextWithScoped<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