haierophanto
haierophanto

Reputation: 51

What is the std::rotate() equivalent in C#?

I'm moving to C# from C++ and I have troubles with translating my project to C#. How to perform

std::rotate(alphabet.rbegin(), alphabet.rbegin() + 1, alphabet.rend());

with the help of C# tools where alphabet is a std::string with basic alphabet.

Upvotes: 0

Views: 341

Answers (1)

V0ldek
V0ldek

Reputation: 10623

There is no standard library function that would do this for you, you need to implement it yourself. Here's probably the simplest way of doing that:

var result = alphabet.Substring(1) + alphabet[0];

This performs two string allocations, one for the Substring and the one for the final result. If your strings are small and this is not a hot path in your code, it'll be enough. If you care about maximising efficiency, use the new string.Create overload from .NET Core 3.0:

var result = string.Create(alphabet.Length, alphabet, (span, source) => 
{
    for (var i = 1; i < source.Length; ++i)
    {
        span[i - 1] = source[i];
    }
    span[source.Length - 1] = source[0];
});

String.Create basically takes some state as its input and then a recipe on how to populate the Span<char> of the new string using that state. In this case, the state is your source alphabet string and the recipe is "iterate over the source skipping its first letter and copy it to the new string, then add the first letter of source at the end".

Note that the second solution is applicable only if you're creating a lot of such rotations. The one-liner is much simpler to understand.

Upvotes: 2

Related Questions