I\'m looking for a way to rotate a string in c++. I spend all of my time in python, so my c++ is very rusty.
Here is what I want it to do: if I have a strin
There is a standard rotate function found in the algorithm header.
If you want to do this yourself, you could try the following:
#include
#include
std::string rotate_string( std::string s ) {
if (s.empty()) return s;
char first = s[0];
s.assign(s, 1, s.size() - 1);
s.append(1, first);
return s;
}
int main() {
std::string foo("abcde");
std::cout << foo << "\t" << rotate_string(foo) << std::endl;
return 0;
}
But of course, using the standard library is preferable here, and in most cases.
EDIT #1 I just saw litb's answer. Beat again!
EDIT #2 I just want to mention that the rotate_string function fails on strings of 0 length. You will get a std::out_of_range error. You can remedy this with a simple try/catch block, or use std::rotate :-)
EDIT #3 Return the same string if the length of the string is 0.