How to reverse a string with C# .NET

This is a straightforward and basic task to implement: given a string input to a function we want to return its reverse.

There’s a wide range of solutions to this problem and here we’ll go through 3 of them using C#:

  • the built-in Reverse extension function
  • the Aggregate LINQ operator
  • bare-bones solution based on a for-loop

Here are the three implementations:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Algorithms
{
    public class StringReverse
    {
        public string ReverseString(string input)
        {
            return ReverseStringWithReverse(input);
            //return ReverseStringWithAggregate(input);
            //return ReverseStringWithLoop(input);
        }

        private string ReverseStringWithReverse(string input)
        {
            var reverse = input.Reverse();
            //return string.Join("", reverse);
            return string.Concat(reverse);
           //or in one line string.Concat(input.Reverse())
        }

        private string ReverseStringWithAggregate(string input)
        {
            return input.Aggregate("", (c1, c2) => c2 + c1);
        }

        private string ReverseStringWithLoop(string input)
        {
            string reversed = "";
            for (int i = input.Length - 1; i >= 0; i--)
            {
                reversed += input[i];
            }
            return reversed;
        }
    }
}

In ReverseStringWithReverse we take the incoming string and apply the built-in Reverse() extension method on it. It returns a collection of chars, i.e. not the reversed string. To join those chars into a string we can call string.Join or string.Concat. Join takes a delimiter which is an empty string in this case as we don’t want to put any extra character in between the characters when they are joined. The Concat function is more straightforward to use, we can just pass in the array collection.

In ReverseStringWithLoop we iterate through the input string starting at the back. We build the reversed string character by character and return the result.

ReverseStringWithAggregate is a bit more “exotic” and uses the Aggregate LINQ operator. I only put it here in case you’d like to show your familiarity with this accumulator function in an interview. If you don’t know how this operator works then you can check out this post for an example. The empty string is a seed which is basically the starting point for building the reversed string.

This overload of the Aggregate function will operate on an IEnumerable<char> as the source string is dissected into its characters. We specified the seed as a string type so the overall result from this extension function will also be a string.

We start with an empty string and apply a function on the source string defined by

(c1, c2) => c2 + c1

This is the accumulator function and accepts two parameters: the first one, i.e. c1 will be of the same type as the seed, i.e. a string. The second one, i.e. c2 will be the same type as each element in the dissected string, i.e. a char. The accumulator function returns the same type as the seed, i.e. a string which is simply built up gradually as

c2 + c1

…i.e. take the character and add it to the growing string c1.

Let’s try to understand this function using the input string “hello”.

So we start with an empty string as c1 and take the first character from the source char collection, i.e. ‘h’. We get "" + 'h' = "h" as the resulting string which will be fed as the c1 string input into the next iteration. So next c1 will be “h” and c2 ‘e’ and we return ‘e’ + “h”, i.e. “eh”. “eh” is taken as c1 in the next round and ‘l’ as the character input, ‘l’ + “eh” will give “leh”. The function continues until we arrive at “olleh”. If we set the seed to “world” then that will be value of c1 in the very first iteration and the end result will be “ollehworld”.

It is probably overkill to use the Aggregate extension for a problem like this but it’s a good opportunity to demonstrate your familiarity with this relatively rarely used function in an interview setting.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

2 Responses to How to reverse a string with C# .NET

  1. Norm says:

    Good stuff! Thanks.

  2. kiquenet says:

    Good !! We need more Andras Nemes in 2021 !!

    About strings, a suggestions: string search algoritms like KPM

    https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: