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.
String-as-Span APIs (C# 6 emulation) is a free C# Academy lesson on CoddyKit — lesson 3 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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);
}
}
Trim by indices
Operate by indices to emulate Span-based Trim logic; no new string created.
using System;
public static class SegText
{
public static ArraySegment<char> Trim(ArraySegment<char> seg)
{
int i = seg.Offset;
int j = seg.Offset + seg.Count - 1;
while (i <= j && Char.IsWhiteSpace(seg.Array[i])) i++;
while (j >= i && Char.IsWhiteSpace(seg.Array[j])) j--;
int n = (j >= i) ? (j - i + 1) : 0;
return new ArraySegment<char>(seg.Array, i, n);
}
}
public class Program
{
public static void Main(string[] args)
{
char[] buf = " Hello, Ada ".ToCharArray();
ArraySegment<char> all = new ArraySegment<char>(buf, 0, buf.Length);
ArraySegment<char> t = SegText.Trim(all);
// Print without creating a new string
for (int k = 0; k < t.Count; k++) Console.Write(t.Array[t.Offset + k]);
Console.WriteLine();
}
}
Search inside window
Build tiny IndexOf-like helpers that return relative positions within the window.
using System;
public static class SegSearch
{
// Find the first index of a char inside the segment; returns -1 if not found.
public static int IndexOf(ArraySegment<char> seg, char needle)
{
int end = seg.Offset + seg.Count;
for (int i = seg.Offset; i < end; i++)
if (seg.Array[i] == needle) return i - seg.Offset; // relative index
return -1;
}
}
public class Program
{
public static void Main(string[] args)
{
char[] buf = "[User: Ada]".ToCharArray();
ArraySegment<char> w = new ArraySegment<char>(buf, 0, buf.Length);
int pos = SegSearch.IndexOf(w, '/'); // 5
Console.WriteLine("pos=" + pos);
}
}
Parse from window
Parse numbers directly from the window without creating substrings; return success/failure.
using System;
public static class SegParse
{
// Try to parse a non-negative integer from the segment; returns false on failure.
public static bool TryParseInt(ArraySegment<char> seg, out int value)
{
value = 0;
if (seg.Count == 0) return false;
int end = seg.Offset + seg.Count;
for (int i = seg.Offset; i < end; i++)
{
char c = seg.Array[i];
if (c < '0' || c > '9') return false;
int digit = (int)(c - '0');
// basic overflow-safe step for small inputs
if (value > (Int32.MaxValue - digit) / 10) return false;
value = value * 10 + digit;
}
return true;
}
}
public class Program
{
public static void Main(string[] args)
{
char[] buf = "id=1203; name=Ada".ToCharArray();
ArraySegment<char> idSeg = new ArraySegment<char>(buf, 3, 4); // "1203"
int n;
bool ok = SegParse.TryParseInt(idSeg, out n);
Console.WriteLine(ok ? ("n=" + n) : "parse failed");
}
}
Boundary materialization
Create a new string only at the final step (UI/logging); keep inner work allocation-free.
using System;
public static class SegToString
{
public static string ToStringSegment(ArraySegment<char> seg)
{
// Materialize a new string only when needed (e.g., logging/output)
return new string(seg.Array, seg.Offset, seg.Count);
}
}
public class Program
{
public static void Main(string[] args)
{
char[] buf = " key=value ".ToCharArray();
ArraySegment<char> all = new ArraySegment<char>(buf, 0, buf.Length);
// Trim first
int i = all.Offset, j = all.Offset + all.Count - 1;
while (i <= j && Char.IsWhiteSpace(buf[i])) i++;
while (j >= i && Char.IsWhiteSpace(buf[j])) j--;
ArraySegment<char> trimmed = new ArraySegment<char>(buf, i, (j >= i) ? (j - i + 1) : 0);
// Create string only at the end
Console.WriteLine(SegToString.ToStringSegment(trimmed)); // "key=value"
}
}
String-as-span approach
Recap
Recap: Treat strings like spans—work on char[] windows, use offset/count for trim/search/parse, and materialize only when needed.
Frequently asked questions
Is the “String-as-Span APIs (C# 6 emulation)” lesson free?
Yes — the full text of “String-as-Span APIs (C# 6 emulation)” is free to read here on the web, and the C# Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “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. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “String-as-Span APIs (C# 6 emulation)” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Span/ReadOnlySpan fundamentals (C# 6 emulation)
- Memory/ReadOnlyMemory emulation: zero-copy windows
- String-as-Span APIs (C# 6 emulation)