Skip to content

Instantly share code, notes, and snippets.

@cslarsen
Created February 16, 2012 19:04
Show Gist options
  • Save cslarsen/1847054 to your computer and use it in GitHub Desktop.
Save cslarsen/1847054 to your computer and use it in GitHub Desktop.
Reverse string in "canonical" C++
/*
* Reverse string in "canonical" C++
*
* Why did I make this a gist? Because I've seen so
* many cumbersome ways of doing this in C++, including
* using <algorithm> and std::reverse, using loops and
* so on. Yeah, those work too, and loops are fine for
* C, but in C++, you should simply just use the iterators
* and standard constructors that std::string gives you.
*
* Source: Christian Stigen Larsen
* http://csl.sublevel3.org
*/
#include <iostream>
#include <string>
/*
* Reverse a std::string in C++.
* No need for <algorithm> or c_str()-wrangling.
*
*/
std::string reverse(const std::string& s)
{
return std::string(s.rbegin(), s.rend());
}
int main()
{
// Outputs "!dlrow ,olleH"
std::cout << reverse("Hello, world!") << std::endl;
return 0;
}
@cslarsen
Copy link
Author

If you do want to do it in place, though, you could do:

#include <algorithm>

void reverse_inplace(std::string& s)
{
  std::reverse(s.begin(), s.end());
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment