c++ - 字符串仅包含有效字符?

标签 c++ string

我想验证一个字符串以检查该字符串是否仅包含有效字符或不使用 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/

相关文章:

c++ - 如何在 C++ 中正确规范化浮点值?

android - 将cpp类添加到android项目中

javascript - 用逗号分割字符串,但在 JavaScript 中不进行转义

c++ - 错误代码 : C2661: no overloaded function takes 6 arguments

c++ - 用定义中的对象数组重载 >> 和 <<

c++ - Clang:x86 FPU 调用约定

php - 如何使用 RegEx 匹配方括号文字?

javascript - jquery字符串比较变量

c - 如何在 printf() 中使用多个精度?

c - 为什么C程序崩溃?