๐ŸŽ“ A1Learner
๐Ÿ”
0 of 28 lessons completed

C# Span and Text

A ReadOnlySpan<char> is a view over the characters of a string. AsSpan creates the view without copying the text.

Finding and parsing inside text

The span views the whole label. IndexOf locates the colon and Parse reads the number after it.

using System;

class Program
{
    static void Main(string[] args)
    {
        ReadOnlySpan<char> text = "id:4521".AsSpan();
        Console.WriteLine(text.IndexOf(':'));
        Console.WriteLine(int.Parse(text.Slice(3)));
    }
}

Testing the start of a span

StartsWith compares the opening characters with another span. The first test passes and the second one fails.

using System;

class Program
{
    static void Main(string[] args)
    {
        ReadOnlySpan<char> text = "hello world".AsSpan();
        Console.WriteLine(text.StartsWith("hello".AsSpan()));
        Console.WriteLine(text.StartsWith("world".AsSpan()));
    }
}

Slicing both sides of a mark

The colon position splits the span into two parts. Each part becomes a string for printing.

using System;

class Program
{
    static void Main(string[] args)
    {
        ReadOnlySpan<char> text = "id:4521".AsSpan();
        int colon = text.IndexOf(':');
        Console.WriteLine(new string(text.Slice(0, colon)));
        Console.WriteLine(new string(text.Slice(colon + 1)));
    }
}

Example

using System;

class Program
{
    static void Main(string[] args)
    {
        ReadOnlySpan<char> text = "name:Hana".AsSpan();
        int colon = text.IndexOf(':');
        ReadOnlySpan<char> namePart = text.Slice(0, colon);
        ReadOnlySpan<char> valuePart = text.Slice(colon + 1);
        Console.WriteLine(new string(namePart));
        Console.WriteLine(new string(valuePart));
        Console.WriteLine(namePart.Length);
    }
}

Key points

  • The AsSpan method turns a string into a ReadOnlySpan<char>.
  • IndexOf finds the position of a character inside the span.
  • Slice returns a smaller span over part of the same text.
  • Parse methods accept a span, so a number can be read without a new string.
  • StartsWith tests the opening characters of a span.
  • new string copies a span of chars into a regular string.

In this example, the span views the text name:Hana. IndexOf finds the colon at position 4. Two slices hold the parts on each side, and the prints show both parts and the length of the first part.

Note

Slicing a span never copies the characters it covers.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does IndexOf return for the span over "id:4521" when it searches for the colon?