php检查字符串是否包含数字,c – 检查字符串是否包含数字的函数

它总是返回false,因为你的逻辑是向后的.您正在使用||运算符== npos检查.如果字符串中缺少任何一个特定数字,则== npos计算结果为true和||很满意,所以你回复假.您需要使用!= npos检查,如果任何检查计算结果为true,则返回true:

bool Person::contains_number(const std::string &c)

{

if (c.find('0') != std::string::npos ||

c.find('1') != std::string::npos ||

c.find('2') != std::string::npos ||

c.find('3') != std::string::npos ||

c.find('4') != std::string::npos ||

c.find('5') != std::string::npos ||

c.find('6') != std::string::npos ||

c.find('7') != std::string::npos ||

c.find('8') != std::string::npos ||

c.find('9') != std::string::npos)

{

return true;

}

return false;

}

要么:

bool Person::contains_number(const std::string &c)

{

return (

c.find('0') != std::string::npos ||

c.find('1') != std::string::npos ||

c.find('2') != std::string::npos ||

c.find('3') != std::string::npos ||

c.find('4') != std::string::npos ||

c.find('5') != std::string::npos ||

c.find('6') != std::string::npos ||

c.find('7') != std::string::npos ||

c.find('8') != std::string::npos ||

c.find('9') != std::string::npos

);

}

一个更简单的解决方案是使用find_first_of()而不是find():

bool Person::contains_number(const std::string &c)

{

return (c.find_first_of("0123456789") != std::string::npos);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值