Reputation: 79
I have the following code:
int main()
{
string adr="bonjour000000";
int j=adr.length();
cout<<adr<<"\nLa longueur de ma chaine est "<<j<<".";
cout<<"\n";
if(adr.length()>=7){
//if(how to test if the characters after the 7th character are =0)
//here begin the 2nd if loop
for(unsigned int i=0; i<adr.length(); i++)
{
cout<<adr[i];
}
adr.erase (adr.begin()+7,adr.end());
cout<<"\n"<<adr;
//here ends the 2nd if loop
}
else{
cout<<"Error: there is less than 7 characters";
cout<<"\n"<<adr;
}
}
I want to test first if adr has 7 or more than 7 characters, then I want to check if all the characters after the 7th characters are all = 0. When this is the case, I would like to cut all these 0, and when not, keep adr as it is. With my example, I expected this output:
bonjour000000
La longueur de ma chaine est 13
bonjour000000
bonjour
Thanks for your help.
Upvotes: 0
Views: 136
Reputation: 258568
The following:
bool condition = (adr.length() > 7) &&
(adr.find_first_not_of('0', 7) == std::string::npos);
Upvotes: 3
Reputation: 31952
You can use std::string::find_first_not_of
to check for the first char that is not a '0'. If there is no such character within the string bounds all of the characters are 0. You will call this on a substring that starts after char #7. You can call it with the starting position as well as @Luchian Grigore has shown
Upvotes: 3