[英]How do I move a character from a position in the string to the very front of it without deleting any character?
我的字符串長約14個字符,我必須將字符從字符串中的某個位置移動到最前面,我無法刪除已經位於myString[0]
的字符。 我該怎么做?
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
請參閱basic_string的相應成員函數。
作為使用std::string
函數的替代方法,您可以嘗試使用<algorithm>
函數。
std::string x = "foobar";
std::rotate(x.begin(), x.begin() + 3, x.begin() + 4); // foobar -> bfooar
要么:
std::reverse(x.begin(), x.begin() + 3); // foobar -> oofbar
std::reverse(x.begin(), x.begin() + 4); // oofbar -> bfooar
這些都不會更改字符串的size()
,也不應該觸發內存重新分配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.