Created
March 13, 2017 16:18
-
-
Save ak9999/1717589062d10c5a57d283daef1c13c6 to your computer and use it in GitHub Desktop.
reverse a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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