我有以下代码:
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;
}
}
如果 adr 有7个或7个以上的字符,我想先测试一下,然后我想检查第7个字符后的所有字符是否全是= 0.在这种情况下,我想要削减所有这些0,如果没有,请保持 adr 不变。 在我的例子中,我期待这个输出:
bonjour000000
La longueur de ma chaine est 13
bonjour000000
bonjour
感谢您的帮助。
答案 0 :(得分:3)
您可以使用std::string::find_first_not_of
检查第一个不是'0'的字符。如果字符串边界内没有这样的字符,则所有字符都为0.您将在char#7之后的子字符串上调用此字符。您可以使用起始位置调用它以及@Luchian Grigore已经显示
答案 1 :(得分:3)
以下内容:
bool condition = (adr.length() > 7) &&
(adr.find_first_not_of('0', 7) == std::string::npos);