Как проверить, содержит ли строка какие-либо цифры в C ++ - PullRequest
6 голосов
/ 27 февраля 2010

Я хочу знать, есть ли в строке какие-либо цифры или нет цифр. Есть ли функция, которая легко это делает?

Ответы [ 6 ]

18 голосов
/ 27 февраля 2010

Возможно следующее:

if (std::string::npos != s.find_first_of("0123456789")) {
  std::cout << "digit(s)found!" << std::endl;
}
7 голосов
/ 27 февраля 2010
boost::regex re("[0-9]");
const std::string src = "test 123 test";
boost::match_results<std::string::const_iterator> what; 
bool search_result = 
   boost::regex_search(src.begin(), src.end(), what, re, boost::match_default);
6 голосов
/ 27 февраля 2010
#include <cctype>
#include <algorithm>
#include <string>

if (std::find_if(s.begin(), s.end(), (int(*)(int))std::isdigit) != s.end())
{
  // contains digit
}
3 голосов
/ 27 февраля 2010

find_first_of, вероятно, ваш лучший выбор, но я играл с гранями iostream, так что вот альтернатива:

if ( use_facet< ctype<char> >( locale() ).scan_is( ctype<char>::digit,
      str.data(), str.data() + str.size() ) != str.data + str.size() )

Измените string на wstring и char на wchar, и у вас теоретически может быть шанс обработать те странные цифры фиксированной ширины, которые используются в некоторых азиатских сценариях.

2 голосов
/ 27 февраля 2010

Нет ничего стандартного для этой цели, но его нетрудно сделать:

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

И вы можете использовать его так:

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

Редактировать:

Или даже лучше версия (поскольку она может работать с любым контейнером, как с const, так и с неконстантными контейнерами):

template <typename InputIterator>
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<CharT>,
                                    std::tr1::placeholders::_1,
                                    std::locale()));
    return it != last;
}

А этот вы можете использовать как:

const std::string str("abcde123xyz");
printf("Has digits: %s\n", has_digits(str.begin(), str.end()) ? "yes" : "no");
2 голосов
/ 27 февраля 2010

задано std :: String s;

if( s.find_first_of("0123456789")!=std::string::npos )
//digits
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...