Skip to content

Instantly share code, notes, and snippets.

@ak9999
Created March 13, 2017 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ak9999/1717589062d10c5a57d283daef1c13c6 to your computer and use it in GitHub Desktop.
Save ak9999/1717589062d10c5a57d283daef1c13c6 to your computer and use it in GitHub Desktop.
reverse a string
// Compile with g++ -std=c++14 reverse.cpp
#include <iostream> // std::cout
#include <string> // std::string
#include <utility> // std::swap
using namespace std;
string reverse(string & s) {
// Ternary conditional
// If string is of even length, n = string length
// If string is of odd length, n = string length divided by 2.
// This way we can reverse strings of both even and odd length.
int n = (s.size() % 2 == 0) ? s.size() - 1 : s.size()/2;
for (int i = 0; i < n; ++i) {
swap(s[i], s[s.size() - i - 1]);
}
return s;
}
int main() {
string str{"Programming is so much fun!"};
string rts{"good"};
cout << str << '\n';
str = reverse(str);
cout << str << '\n';
cout << '\n';
cout << rts << '\n';
rts = reverse(rts);
cout << rts << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment