noobtuts

C++ Reverse a String

Foreword

Today we will learn how to reverse a string. For example, how to convert "abc123" to "321cba".

Implementation

The only complicated part about this is the -1 behind length(). Without this we would get access violation errors, so let's make sure this won't happen:

std::string reverse(std::string& s)
{
    std::string result;
   
    for (unsigned int i = 0; i < s.length(); ++i)
    {
        result += s.at( s.length()-1 -i );
    }
   
    return result;
}

Example

std::cout<<reverse("ABC"); // will give CBA

It's very simple and it works great.

Summary

A simple function, yet a very important part of our library. It will be needed in most of the games, and we will be happy to already have it implemented when it comes to that point.