Rotate a string in c++?

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]);
}

Here's a relatively simple way:

void RotateStringInPlace(char buffer[])
{
    // Get the length of the string.

    int len  = strlen(buffer);
    if (len == 0) {
        return;
    }

    // Save the first character, it's going to be overwritten.

    char tmp = buffer[0];

    //  Slide the rest of the string over by one position.

    memmove(&buffer[0], &buffer[1], len - 1);

    // Put the character we saved from the front of the string in place.

    buffer[len - 1] = tmp;
    return;
}

Note that this will modify the buffer in place.


I recommend std::rotate:

std::rotate(s.begin(), s.begin() + 1, s.end());

Tags:

C++

String