C++ 确定字符串是否仅包含字母数字字符(或空格)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2926878/
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
Determine if a string contains only alphanumeric characters (or a space)
提问by dreamlax
I am writing a function that determines whether a string contains only alphanumeric characters and spaces. I am effectively testing whether it matches the regular expression ^[[:alnum:] ]+$
but without using regular expressions. This is what I have so far:
我正在编写一个函数来确定字符串是否只包含字母数字字符和空格。我正在有效地测试它是否与正则表达式匹配,^[[:alnum:] ]+$
但不使用正则表达式。这是我到目前为止:
#include <algorithm>
static inline bool is_not_alnum_space(char c)
{
return !(isalpha(c) || isdigit(c) || (c == ' '));
}
bool string_is_valid(const std::string &str)
{
return find_if(str.begin(), str.end(), is_not_alnum_space) == str.end();
}
Is there a better solution, or a “more C++” way to do this?
有没有更好的解决方案,或者“更多 C++”的方法来做到这一点?
采纳答案by jopa
Looks good to me, but you can use isalnum(c)
instead of isalpha
and isdigit
.
对我来说看起来不错,但您可以使用andisalnum(c)
代替。isalpha
isdigit
回答by R Samuel Klatchko
And looking forward to C++0x, you'll be able to use lambda functions (you can try this out with gcc 4.5 or VS2010):
期待 C++0x,您将能够使用 lambda 函数(您可以使用 gcc 4.5 或 VS2010 来尝试):
bool string_is_valid(const std::string &str)
{
return find_if(str.begin(), str.end(),
[](char c) { return !(isalnum(c) || (c == ' ')); }) == str.end();
}
回答by R Samuel Klatchko
You can also do this with binders so you can drop the helper function. I'd recommend Boost Bindersas they are much easier to use then the standard library binders:
您也可以使用活页夹来执行此操作,这样您就可以删除辅助函数。我推荐Boost Binder,因为它们比标准库 Binder 更容易使用:
bool string_is_valid(const std::string &str)
{
return find_if(str.begin(), str.end(),
!boost::bind(isalnum, _1) || boost::bind(std::not_equal_to<char>, _1, ' ')) == str.end();
}
回答by Ilkka
Minor points, but if you want is_not_alnum_space() to be a helper function that is only visible in that particular compilation unit, you should put it in an anonymous namespace instead of making it static:
次要问题,但如果您希望 is_not_alnum_space() 成为仅在该特定编译单元中可见的辅助函数,则应将其放在匿名命名空间中,而不是使其成为静态:
namespace {
bool is_not_alnum_space(char c)
{
return !(isalpha(c) || isdigit(c) || (c == ' '));
}
}
...etc