How to test if a string contains any digits in C++

前端 未结 6 1554
日久生厌
日久生厌 2020-12-11 05:49

I want to know if a string has any digits, or if there are no digits. Is there a function that easily does this?

6条回答
  •  伪装坚强ぢ
    2020-12-11 06:36

    There's nothing standard for the purpose, but it's not difficult to make one:

    template 
    bool has_digits(std::basic_string &input)
    {
        typedef typename std::basic_string::iterator IteratorType;
        IteratorType it =
            std::find_if(input.begin(), input.end(),
                         std::tr1::bind(std::isdigit,
                                        std::tr1::placeholders::_1,
                                        std::locale()));
        return it != input.end();
    }
    

    And you can use it like so:

    std::string str("abcde123xyz");
    printf("Has digits: %s\n", has_digits(str) ? "yes" : "no");
    

    Edit:

    Or even better version (for it can work with any container and with both const and non-const containers):

    template 
    bool has_digits(InputIterator first, InputIterator last)
    {
        typedef typename InputIterator::value_type CharT;
        InputIterator it =
            std::find_if(first, last,
                         std::tr1::bind(std::isdigit,
                                        std::tr1::placeholders::_1,
                                        std::locale()));
        return it != last;
    }
    

    And this one you can use like:

    const std::string str("abcde123xyz");
    printf("Has digits: %s\n", has_digits(str.begin(), str.end()) ? "yes" : "no");
    

提交回复
热议问题