I want to know if a string has any digits, or if there are no digits. Is there a function that easily does this?
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");