1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

お姉さんとイケないことシない? - 不変である string の変更

Last updated at Posted at 2024-05-28

というわけで 備忘録的な話ですが、C# の string は不変な文字列です。直接的な操作することはできず、基本的に新たな文字列が生成されます。

また、 string からは Span<T> ではなく、 ReadOnlySpan<T> が取得されるので変更することもできません。

ただ、 ReadOnlySpan<T> は unsafe を使わずに……つまり、合法的に Span<T> を取得する手段が無いわけではないです。

というのが、今回の趣旨です。

この記事は ReadOnlySpan<T> から Span<T> を取得したり、配列から範囲外を含む Span<T> を取得したりしていますが、それを推奨する記事ではないです。
そういう手段が存在するというのを伝える為の記事です。

やってみる

using System;
using System.Runtime.InteropServices;

var text = "hello world!";
var span = MemoryMarshal.CreateSpan(ref MemoryMarshal.GetReference(text.AsSpan()), text.Length);
span[6] = 'W';
Console.WriteLine(text);

sharplab

output
hello World!

設定した hello world! ではなく hello World! と出ています。

以上。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?