StringBuilder.GetChunks Method
Definition
Returns an object that can be used to iterate through the chunks of characters represented in a ReadOnlyMemory<Char>
created from this StringBuilder instance.
public:
System::Text::StringBuilder::ChunkEnumerator GetChunks();
public System.Text.StringBuilder.ChunkEnumerator GetChunks ();
member this.GetChunks : unit -> System.Text.StringBuilder.ChunkEnumerator
Public Function GetChunks () As StringBuilder.ChunkEnumerator
Returns
An enumerator for the chunks in the ReadOnlyMemory<Char>
.
Remarks
You can iterate the chunks in the memory range with code like the following:
foreach (ReadOnlyMemory<char> chunk in sb.GetChunks())
foreach(char ch in chunk.Span)
{ /* operations on ch */ }
The purpose of this method is to efficiently extract the data of a constant StringBuilder. If the StringBuilder is modified while the chunk enumeration is incomplete, the result is undefined. StringBuilder is also not thread-safe, so operating on it with concurrent threads is illegal.
The ReadOnlyMemory<T> chunks returned are not guaranteed to remain unchanged if the StringBuilder is modified, so do not cache them for later use.
Creating a ReadOnlySpan<T> from a ReadOnlyMemory<T> (as the ReadOnlyMemory<T>.Span method does in the previous example) is expensive, so create a local variable for the span if you need to use it in a nested for
statement. For example:
foreach (ReadOnlyMemory<char> chunk in sb.GetChunks())
{
var span = chunk.Span;
for(int i = 0; i < span.Length; i++)
{
/* operations on span[i] */
}
}