确定是否字符串只包含字母数字字符(或空格)空格、字符串、字母、字符

2023-09-11 00:05:58 作者:时光匆匆的小流年

我学习C ++和我写一个函数,确定一个字符串是否只包含字母数字字符和空格。我想我有效地测试它是否符合常规的前pression ^ [[:alnum:]] + $ ,但没有使用常规的EX pressions。我已经看到了很多的算法迭代器左右旋转,所以我试图找到利用迭代器的解决方案,而这就是我:

I'm learning C++ and I am writing a function that determines whether a string contains only alphanumeric characters and spaces. I suppose I am effectively testing whether it matches the regular expression ^[[:alnum:] ]+$ but without using regular expressions. I have seen a lot of algorithms revolve around iterators, so I tried to find a solution that made use of iterators, and this is what I have:

#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();
}

有没有更好的解决方案,或者和ldquo;更多的C ++&rdquo;的办法做到这一点?

Is there a better solution, or a “more C++” way to do this?

推荐答案

我看不错,但你可以用字符isalnum(C)而不是因而isalpha ISDIGIT

Looks good to me, but you can use isalnum(c) instead of isalpha and isdigit.