Reputation:
My string is about 14 characters long and I have to move a character from somewhere in the string to the very front and I can not delete the character that already sits in myString[0]
. How do I do it?
Upvotes: 0
Views: 6305
Reputation: 18652
As an alternative to using std::string
functions, you could try functions from <algorithm>
.
std::string x = "foobar";
std::rotate(x.begin(), x.begin() + 3, x.begin() + 4); // foobar -> bfooar
or:
std::reverse(x.begin(), x.begin() + 3); // foobar -> oofbar
std::reverse(x.begin(), x.begin() + 4); // oofbar -> bfooar
Neither of these change the string's size()
and shouldn't trigger a memory reallocation.
Upvotes: 1
Reputation: 59811
std::string x = "foobar";
x.insert(0, 1, x[3]); // insert the 4th character at the beginning
x.erase(4, 1); // erase the 5th character
// (5th because the preceding operation added a character
See the respective member functions of basic_string.
Upvotes: 1