ExtensionMethod.NET Home of 876 C#, Visual Basic, F# and Javascript extension methods

Repeated

Extremely fast string repeater complete with alternate extension for char spans.

Source

using System;

public static class StringExtensions
{
    public static string Repeated(this string text, int count)
    {
        if (text.Length == 0 || count < 1)
            return "";

        if (count == 1)
            return text;

        if (text.Length == 1)
            return new string(text[0], count);

        return Repeat(text, count);
    }

    public static string Repeated(this ReadOnlySpan<char> text, int count)
    {
        if (text.IsEmpty || count < 1)
            return "";

        if (count == 1)
            return new string(text);

        if (text.Length == 1)
            return new string(text[0], count);

        return Repeat(text, count);
    }

    #pragma warning disable CS8500
    private static string Repeat(ReadOnlySpan<char> text, int count)
    {
        unsafe
        {
            var result = string.Create(
                text.Length * count,
                new nint(&text),
                static (span, state) =>
                {
                    var text = *(ReadOnlySpan<char>*)state.ToPointer();
                    text.CopyTo(span);
                    int copied = text.Length;
                    while (copied < span.Length)
                    {
                        int toCopy = Math.Min(copied, span.Length - copied);
                        span[..toCopy].CopyTo(span[copied..]);
                        copied += toCopy;
                    }
                });

            return result;
        }
    }
    #pragma warning restore CS8500
}

Example

string extremeLaughter = "HA".Repeated(16);

Console.WriteLine(extremeLaughter);

Author: Kelly Brown

Submitted on: 14 jun 2023

Language: csharp

Type: System.String

Views: 1252