如何测试字符串是否包含 C++ 中的任何数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2346599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to test if a string contains any digits in C++
提问by neuromancer
I want to know if a string has any digits, or if there are no digits. Is there a function that easily does this?
我想知道一个字符串是否有任何数字,或者是否没有数字。有没有一个功能可以轻松做到这一点?
回答by
Perhaps the following:
也许如下:
if (std::string::npos != s.find_first_of("0123456789")) {
std::cout << "digit(s)found!" << std::endl;
}
回答by
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);
回答by newacct
#include <cctype>
#include <algorithm>
#include <string>
if (std::find_if(s.begin(), s.end(), (int(*)(int))std::isdigit) != s.end())
{
// contains digit
}
回答by Potatoswatter
find_first_of
is probably your best bet, but I've been playing around with iostream facets so here's an alternative:
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() )
Change string
to wstring
and char
to wchar
and you might theoretically have a chance at handling those weird fixed-width digits used in some Asian scripts.
更改string
为wstring
和char
,wchar
理论上您可能有机会处理某些亚洲文字中使用的那些奇怪的固定宽度数字。
回答by KitsuneYMG
given std::String s;
给定 std::String s;
if( s.find_first_of("0123456789")!=std::string::npos )
//digits
回答by Dmitry
There's nothing standard for the purpose, but it's not difficult to make one:
没有什么标准可以达到这个目的,但制作一个并不难:
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();
}
And you can use it like so:
你可以像这样使用它:
std::string str("abcde123xyz");
printf("Has digits: %s\n", has_digits(str) ? "yes" : "no");
Edit:
编辑:
Or even betterversion (for it can work with any container and with both const and non-const containers):
或者甚至更好的版本(因为它可以与任何容器以及常量和非常量容器一起使用):
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;
}
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");