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
Here's a solution that "floats" the first character to the end of the string, kind of like a single iteration of bubble sort.
#include <algorithm>
string rotate(string s) {
for (int i = 1; i < s.size(); i++)
swap(s[i-1], s[i]);
return s;
}
if you want the function to rotate the string in-place:
#include <algorithm>
void rotate(string &s) {
for (int i = 1; i < s.size(); i++)
swap(s[i-1], s[i]);
}
There is a standard rotate function found in the algorithm header.
If you want to do this yourself, you could try the following:
#include <iostream>
#include <string>
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.
At some point i was obsessed with divide and conquer, and used the following
since it 'Divides' the problem to smaller problems my guess is that this performs better. Expert comments on complexity and memory access behavior are welcome :).
Initial Call:
rotate_about(rots_g, 0, i, j - 2);
void rotate_about(char *str, int start, int pivot, int end)
{
if(pivot == start)
{
return ;
}
else if((pivot - start) <= (end - pivot))
{
int move_bytes = pivot-start;
swap_bytes(&str[start], &str[pivot],move_bytes);
rotate_about(str,pivot,pivot+move_bytes,end);
}
else
{
int move_bytes = end - pivot + 1;
swap_bytes(&str[start], &str[pivot],move_bytes);
rotate_about(str, start+move_bytes ,pivot,end);
}
}