我正在尝试从字符串中截断开头的零,所以我使用了序列删除功能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;
我得到的输出字符串是
0010557
而不是 10557
和调试语句打印:0 000010557
0 00010557
1 0010557
我阅读了 erase 的文档和 this后思考可能会有一些迭代器失效,但实现接受的答案中推荐的代码片段也给出了相同的输出,请帮助我了解问题出在哪里。
我是使用STL库函数的新手,所以请原谅我的任何疏忽,谢谢。
最佳答案
您的 for
循环增加 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;
}
输出:
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;
}
关于c++ - 使用 std::string::erase 从字符串中删除起始字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61835663/