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

neu*_*cer 6 c++ string

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

小智 18

也许如下:

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


Ser*_*kov 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);
Run Code Online (Sandbox Code Playgroud)


new*_*cct 6

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

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

  • 这是因为来自`<cctype>`的`isdigit`已经是一个类型为`int(*)(int)`的函数.`std :: isdigit`是一个模板,所以没有强制转换它是模糊的.它位于`<locale>`,但我希望你从`<string>`中选择它.所以一旦`<cctype>`做了它的事情,我们不确定它是否符合但是肯定是常见的,`:: isdigit`明确地是一个特定的函数,而`std :: isdigit`是作为函数重载的` <cctype>`加上来自`<locale>`的模板.模板的实例化都没有返回类型`int`,但没有强制转换它们不能被排除. (2认同)