C++ Kata - Reversed Strings

By Lochard | As a newbie programmer | 21 Sep 2022



Learning from YayoDrayber, I am sharing my CodeWars Kata which could also be a reference for myself in the future.

 

This is the same as the last Kata but in C++. I switch to C++ because Publish0x doesn't have highlight for Rust.

 

DESCRIPTION:

Complete the solution so that it reverses the string passed into it.

'world' => 'dlrow'

'word' => 'drow'

 

Starting code

#include <string>
using namespace std ; 

string reverseString (string str )
{
  // your Code is Here ... enjoy !!!
  return 1 ;
}

My attempt. There was a blank space before the semicolon on the line 2. 😅

#include <string>
using namespace std ; 

string reverseString (string str )
{
  // your Code is Here ... enjoy !!!
  string s = "";
  for (char ch : str)
    s = ch + s;

  return s;
}

Best Practice

#include <algorithm>
#include <string>

std::string reverseString(const std::string& str) {
  return std::string(str.rbegin(), str.rend());
}

Using reverse()

#include <algorithm>
#include <string>

std::string reverseString(std::string str) {
  std::reverse(str.begin(), str.end());
  return str;
}

Using push_back()

#include <string>
#include <iostream>

std::string reverseString(std::string str)
{
    std::string rev;
    for (int i = str.length() - 1; i >= 0; i--)
    {
        rev.push_back(str[i]);

    }

    return rev;
}

My postkata snippet

#include <string>

std::string reverseString (std::string str ) {
  return std::string(str.rbegin(), str.rend());
}

How do you rate this article?

0


Lochard
Lochard

20240228 Arrived in the UK for about 2 week. All my fears persist. Some are even getting worse. https://github.com/locharp/asylum_diary/


As a newbie programmer
As a newbie programmer

Sharing entry level codes. My snippets on GitHub https://github.com/locharp/code-snippets

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.