Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a C# string to a Span<char>? (Span<T>)

Tags:

c#

c#-7.2

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

Span<char> mySpan = "My sample source string"; 
like image 871
Dan Sorensen Avatar asked Nov 16 '17 04:11

Dan Sorensen


People also ask

What is the easiest way to convert Celsius to Fahrenheit?

To convert temperatures in degrees Celsius to Fahrenheit, multiply by 1.8 (or 9/5) and add 32.

How do you calculate Celsius?

In other words, if you'd like to convert a temperature reading in Fahrenheit to Celsius: Start with the temperature in Fahrenheit (e.g., 100 degrees). Subtract 32 from this figure (e.g., 100 - 32 = 68). Divide your answer by 1.8 (e.g., 68 / 1.8 = 37.78)


1 Answers

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).

like image 139
gfoidl Avatar answered Sep 28 '22 11:09

gfoidl