Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate a string in c++?

Tags:

c++

string

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 string 'abcde' I want it changed to 'bcdea' (first character moved to the end). Here is how I did it in python:

def rotate(s):
    return s[1:] + s[:1]

I'm not sure how to do it in cpp. Maybe use an array of chars?

like image 345
Jeremy Avatar asked Apr 25 '09 18:04

Jeremy


2 Answers

I recommend std::rotate:

std::rotate(s.begin(), s.begin() + 1, s.end());
like image 151
Johannes Schaub - litb Avatar answered Oct 04 '22 03:10

Johannes Schaub - litb


If you don't want these in-place solutions, then your python code can be directly translated to C++, with a bit of extra code to deal with the fact that index out of bounds is bad news in C++.

s[1:] --> s.substr(1);
s[:1] --> s[0]; // s[0] is a char not a string, but that's good enough

So,

std::string rotate(const std::string &s) {
    if (s.size() > 0) return s.substr(1) + s[0];
    return s;
}

This isn't the most efficient: it will almost certainly do more string creation than the minimum possible. But you don't usually need the most efficient, and you have reserve and append if you want to do concatenation without unnecessary allocation.

like image 21
Steve Jessop Avatar answered Oct 04 '22 04:10

Steve Jessop