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

一个人想着一个人 提交于 2019-12-01 14:57:49

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

Dan Sorensen 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.

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

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!