【发布时间】:2010-02-27 07:53:05
【问题描述】:
我想知道一个字符串是否有数字,或者是否没有数字。有没有一个功能可以轻松做到这一点?
【问题讨论】:
我想知道一个字符串是否有数字,或者是否没有数字。有没有一个功能可以轻松做到这一点?
【问题讨论】:
也许如下:
if (std::string::npos != s.find_first_of("0123456789")) {
std::cout << "digit(s)found!" << std::endl;
}
【讨论】:
find_if 或 find_any 更快,只需要 O(n) 步。
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);
【讨论】:
#include <cctype>
#include <algorithm>
#include <string>
if (std::find_if(s.begin(), s.end(), (int(*)(int))std::isdigit) != s.end())
{
// contains digit
}
【讨论】:
isdigit 之前的std:: 部分,也没有必要。有人知道为什么会这样吗?
<cctype> 包括 Unix/C <ctype.h> 并使用 using 导入其内容,至少在 Mac OS X 上。 §17.4.1.2/4 似乎说这种方法是非法的,<cctype> 不应该定义::isdigit。会不会是故意不合格?
ctype,而且适用于整个 C 标准库。无论如何,这并不能回答为什么前面带有 std:: 的版本需要演员表。
<cctype> 的isdigit 已经是一个类型为int(*)(int) 的函数。 std::isdigit 是一个模板,所以没有演员表是模棱两可的。它在<locale>,但我希望你是从<string> 获取的。所以一旦<cctype> 完成了它的事情,我们不确定它是否符合但肯定很常见,::isdigit 无疑是一个特定的函数,而std::isdigit 被重载为来自<cctype> 的函数加上来自@ 的模板987654341@。模板的所有实例都没有返回类型int,但如果没有强制转换,它们不能被排除。
locale
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,理论上您可能有机会处理某些亚洲文字中使用的那些奇怪的固定宽度数字。
【讨论】:
给定 std::String s;
if( s.find_first_of("0123456789")!=std::string::npos )
//digits
【讨论】:
目的没有标准,但制作一个并不难:
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");
【讨论】: