user1906594
user1906594

Reputation:

How do I move a character from a position in the string to the very front of it without deleting any character?

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

Answers (2)

Blastfurnace
Blastfurnace

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

pmr
pmr

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

Related Questions