Skip to content

Reverse String

Intro

Reverse a string

For example: input: "cool" output: "looc"

Task

Reverse a string

The Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#if !defined(REVERSE_STRING_H)
#define REVERSE_STRING_H

#include "string"

namespace reverse_string {
std::string reverse_string(std::string test);
} // namespace reverse_string

#endif // REVERSE_STRING_H
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include "reverse_string.h"
#include <algorithm>
#include <iterator>
#include <string>

namespace reverse_string {
std::string reverse_string(std::string test);
} // namespace reverse_string

std::string reverse_string::reverse_string(std::string test) {
  std::reverse_iterator<std::string::iterator> r = test.rbegin();
  std::string rev(r, test.rend());
  return rev;
}

Last update: February 8, 2021

Comments