我正在编写一个函数来确定字符串是否仅包含字母数字字符和空格。我正在有效地测试它是否匹配正则表达式 ^[[: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();
}
有没有更好的解决方案,或者“更多的 C++”方法来做到这一点?
原文由 dreamlax 发布,翻译遵循 CC BY-SA 4.0 许可协议
对我来说看起来不错,但您可以使用
isalnum(c)
而不是isalpha
和isdigit
。