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?
I recommend std::rotate
:
std::rotate(s.begin(), s.begin() + 1, s.end());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With