c++ - 使用 std::string::erase 从字符串中删除起始字符

标签 c++ string stl

我正在尝试从字符串中截断开头的零,所以我使用了序列删除功能
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/

相关文章:

c++ - 模板友元函数实例化

c++ - 如何在C++中读取同时包含整数和特殊字符的txt文件

c++ - 为什么我不能在 C++ 中使用不同的指针访问 int?

c - 在套接字 C 中发送字符串?

.net - .NET 中应该将常量字符串存储在哪里

c++ - 在 ECS 模型中,最合适的观察者容器是什么?

c++ - 如何检查 A+B 是否超过 long long? (A和B都是长长的)

javascript - jQuery:向日期字符串添加前导零

C++ 为容器编写分配过程

C++ 移入容器