You Split on Each Character, of Course

I like to practice coding on exercism.io. If you haven’t seen it before, it’s a site that gives you little toy problems that you can solve and submit, whereafter your peers can give you feedback on the solution. I was working on a problem to reverse strings. I thought:

Easy! I’ll just split the string on each character, iterate over the resulting array backwards, push each character into a new array and then join that array into a string!

So, I did just that:

using System;
using System.Collections.Generic;
using System.Linq;

public static class ReverseString
{
    public static string Reverse(string input)
    {
        var chars = input.ToCharArray();
        var reversed = new List<char>();

        for (int i = input.Length - 1; i >= 0; i--)
        {
            reversed.Add(chars[i]);
        }

        return string.Join(string.Empty, reversed);
    }
}

Strings are Arrays

I don’t know why I always forget this, but: strings are arrays of characters! You can iterate over them, just like any other array. This is one of those things that, unless I’m writing string manipulation code daily, I tend to forget. Maybe writing a blog post about it will help me remember. Armed with my freshly-jogged memory, I updated my solution to:

public static class ReverseString
{
    public static string Reverse(string input)
    {
        var reversed = string.Empty;

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

        return reversed;
    }
}

The (re)learning never stops. Happy coding!