我想验证一个字符串以检查该字符串是否仅包含有效字符或不使用 C++。
Valid characters should be given to the
function
like as charset of valid characters: "abc123".
仅包含上述字符集中给定字符的字符串应返回 true
,而还包含其他给定字符的字符串应返回 false
。显然是一项简单的任务:)
--> 使用字符集 abc123
:
string myString_1 = "bbbac1" // should get true
string myString_2 = "bbbac132aacc" // should get true
string myString_3 = "xxxxxx" // should get false
string myString_4 = "bbbac12533cc" // should get false
如何在 C++ 中实现这样的调用?
注意:我虽然考虑使用类似下面代码的东西,但我很确定有更好的解决方案。
string charset = "abc123";
string myString = "bbbac1";
for (int i=0; i<charset.length(); i++) {
std::replace( myString.begin(), myString.end(), charset[i], '');
}
bool isValid = (myString.length() == 0);
最佳答案
正如 igor-tandetnik 在评论中指出的,这是 std::find_first_not_of
的工作:
auto validate(const std::string& str, const std::string& charset) -> bool
{
return str.find_first_not_of(charset) == std::string::npos;
}
关于c++ - 字符串仅包含有效字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50437439/