output should be 12 not 102 why is it not deleting all the zeros
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s="10002";
for(int i=0;i<s.size();i++)
if(s[i]=='0')
s.erase(s.begin()+i);
cout<<s;
}
output should be 12 not 102 why is it not deleting all the zeros
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s="10002";
for(int i=0;i<s.size();i++)
if(s[i]=='0')
s.erase(s.begin()+i);
cout<<s;
}
It’s skipping a value because the loop counter gets incremented even when you erase characters. You need to decrement i
when you erase a 0
if (s[i] == 0) {
s.erase(s.begin() + i);
i--;
}
Let's dry run your code.
i = 0, s[0] != '0'
(does nothing)i = 1, s[1] = '0'
(it erases the '0'
at second index, now the string is "1002")i = 2, s[2] = '0'
(it erases the '0'
at third index, now the string is "102"
)i = 3
, but the size of string is also 3
, so the loop breaks because of the condition i<s.size()
.Hence 102
is printed.
As @DanMulin mentioned, it's skipping value because when you deleted a character, the std::string
size is decreased but i
keeps getting increased. To solve it, add a i--
.
#include <iostream>
#include <string>
int main()
{
std::string s="10002";
for(int i=0; i<s.size(); i++)
{
if(s[i]=='0')
{
s.erase(s.begin()+i); i--;
}
}
std::cout << s;
}
Or to avoid this all together, you can use a while
loop instead (which I recommended more when manipulating std::strings
):
#include <iostream>
#include <string>
int main()
{
std::string s="10002";
int inc = 0;
while(inc < s.length())
{
while(s[inc] == '0') { s.erase(s.begin()+inc); }
inc++;
}
std::cout << s;
}
Also, see