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());
}