[英]Removing starting characters from string using std::string::erase
我試圖從字符串中截斷開頭的零,所以我使用了序列擦除 function
string& erase (size_t pos = 0, size_t len = npos);
這是我的實現:
string str="000010557";
for(char c:str){
cout<<c<<" "<<str<<" "<<"\n";// for debug purpose
if(c=='0')
str.erase(0,1);
else
break;
}
cout<<str;
我得到的 output 字符串是0010557
而不是10557
和調試語句打印:
0 000010557
0 00010557
1 0010557
我閱讀了擦除的文檔, 這篇文章認為可能存在一些迭代器失效,但實施已接受答案中推薦的代碼片段也給出了相同的 output,請幫助我了解問題出在哪里。
我是使用 stl 庫函數的新手,所以請原諒我的任何疏忽,謝謝。
您for
循環正在遞增 position 從中提取c
,即使您刪除了前導零。 因此,在循環運行兩次之后,您已經擦除了前導零的第一個和第三個,那么c
值將是第一個1
。
這是嘗試跟蹤代碼中發生的情況:
Start of first loop:
"000010557"
^
c is '0', so erase is called, making the string:
"00010557"
At the end of this first loop, the position is incremented, so...
Start of second loop:
"00010557"
^ (Note that we've skipped a zero!)
c is '0', so erase is called, making the string:
"0010557"
End of loop, position increment, and we skip another zero, so...
Start of third loop:
"0010557"
^
c is not '0', so we break out of the loop.
相反,您應該使用while
循環,只測試第一個字符:
int main()
{
string str = "000010557";
char c;
while ((c = str.at(0)) == '0') {
cout << c << " " << str << " " << "\n";// for debug purpose
str.erase(0, 1);
}
cout << str;
}
Output:
0 000010557
0 00010557
0 0010557
0 010557
10557
當然,您的“調試”行只需要c
變量,因此,沒有它,您只需:
int main()
{
string str = "000010557";
while (str.at(0) == '0') str.erase(0, 1);
cout << str;
}
即使你讓這段代碼工作,它也不是一個好的解決方案。 從字符串前面刪除單個字符意味着將所有后續字符向下移動一個 position,並且代碼對每個前導零都執行此操作。 相反,計算前導零並立即將它們全部刪除:
std::string::size_type non_zero_pos = 0;
while (non_zero_pos < str.size() && str[non_zero_pos] == '0')
++non_zero_pos;
str.erase(0, non_zero_pos);
這樣,(昂貴的)擦除操作只進行一次。
或者使用迭代器:
auto non_zero_it = std::find_first_not_of(std::begin(str), std::end(str), "0");
str.erase(std::begin(str), non_zero_it);
編輯:固定搜索非 0 迭代器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.