String-as-Span APIs (C# 6 emulation)
Emulate string-as-span: convert to char[], slice with ArraySegment , search/trim/parse by indices, and create substrings only at the edges.
Plan: string as slices
Aim: Use string-as-span ideas on C# 6.
- Convert once to char[]
- Use ArraySegment<char> as a view
- Trim/search/parse by indices
- Substring only at the boundary
Window over string
Create a window over the string by converting once to char[], then work with offset/count.
using System;
public static class StrWin
{
public static ArraySegment<char> Window(string s, int start, int count)
{
if (s == null) throw new ArgumentNullException("s");
if (start < 0 || count < 0 || start + count > s.Length) throw new ArgumentOutOfRangeException();
// Convert once: keep char[] for further operations
char[] buf = s.ToCharArray();
return new ArraySegment<char>(buf, start, count);
}
}
public class Program
{
public static void Main(string[] args)
{
string text = " [User: Ada] ";
ArraySegment<char> mid = StrWin.Window(text, 2, 10); // "[User: Ada]"
Console.WriteLine("Offset=" + mid.Offset + " Count=" + mid.Count);
}
}
All lessons in this course
- Span/ReadOnlySpan fundamentals (C# 6 emulation)
- Memory/ReadOnlyMemory emulation: zero-copy windows
- String-as-Span APIs (C# 6 emulation)