如何测试字符串是否包含C ++中的任何数字

时间:2010-02-27 07:53:05

标签: c++ string

我想知道字符串是否有任何数字,或者是否没有数字。有没有一个功能很容易做到这一点?

6 个答案:

答案 0 :(得分:18)

或许如下:

if (std::string::npos != s.find_first_of("0123456789")) {
  std::cout << "digit(s)found!" << std::endl;
}

答案 1 :(得分:7)

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);

答案 2 :(得分:6)

#include <cctype>
#include <algorithm>
#include <string>

if (std::find_if(s.begin(), s.end(), (int(*)(int))std::isdigit) != s.end())
{
  // contains digit
}

答案 3 :(得分:3)

find_first_of可能是你最好的选择,但我一直在玩iostream facets,所以这里有另一种选择:

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,理论上您可能有机会处理某些亚洲脚本中使用的那些奇怪的固定宽度数字。

答案 4 :(得分:2)

给出std :: String s;

if( s.find_first_of("0123456789")!=std::string::npos )
//digits

答案 5 :(得分:2)

目的没有标准,但制作一个并不困难:

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和非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");
相关问题