38

How do I convert a string to a Span<T>?

Span<char> mySpan = "My sample source string";
Dan Sorensen
  • 11,403
  • 19
  • 67
  • 100

3 Answers3

51

Span<T> and friends are included in .NET Core 2.1, so no additional NuGet package needs to be installed.

Dan Sorensen's answer was correct at that date and based on the preview, but now it is outdated. For string, the extension methods are AsSpan and AsMemory, that return ReadOnlySpan<char> and ReadOnlyMemory<char> respectively.

Explicit AsReadOnlySpan is gone, because strings are immutable, so it makes no sense to get back a Span<char> (that is writeable).

Pang
  • 9,564
  • 146
  • 81
  • 122
gfoidl
  • 890
  • 10
  • 8
  • Thank you for this answer. Was doing a direct search for `AsReadOnlySpan` but was not turning up even though `AsSpan` returns `ReadOnlySpan`, doh. – Mike-E May 20 '18 at 16:36
23

You need to install the System.Memory NuGet package.

There are extension methods for strings called .AsSpan() or .AsReadOnlySpan() to convert a string to the appropriate Span<T>.

Example:

Span<char> mySpan = "My sample source string".AsSpan();
ReadOnlySpan<char> myReadOnlySpan = "My read only string".AsReadOnlySpan();

Source: MSDN Channel 9 "C# 7.2: Understanding Span" (around the 6 minute mark)

Update: this answer was correct at the time, but based on a preview version. See updated answer on this page by gfoidl for current procedure.

Dan Sorensen
  • 11,403
  • 19
  • 67
  • 100
3

Provided you are on .NET Core/5+ or have the NuGet packages installed (see other answers), you can create a Span<char> from string as so:

string str = "My sample source string";
Span<char> mySpan = stackalloc char[str.Length]; // or `new char[str.Length]`
str.AsSpan().CopyTo(mySpan);
Tinister
  • 11,097
  • 6
  • 35
  • 36