Reputation:
I'd like to valid a string to check if the string just includes valid characters or not using C++.
Valid characters should be given to the
function
like as charset of valid characters: "abc123".
A string that just includes the characters given in the charset above should return true
while a string that also includes other characters then given should return false
. Obviously a easy task :)
--> using charset 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
How can I implement a call like this in C++?
Note: I though about using something like the code below but I'm pretty sure theres a way better solution.
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);
Upvotes: 0
Views: 756
Reputation: 75924
AS igor-tandetnik pointed in comments this is a job for 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;
}
Upvotes: 1
Reputation: 473
You can write your own check function:
bool checkstring(std::string &checkstring, std::string &legalchars) {
for (char c : checkstring) {
// resetting the bool
bool isLegal = false;
for (char d : legalchars) {
// comparing the chars
if (c == d) { isLegal = true; }
}
// if a non-legal char was found, return false
if (!isLegal) { return false; }
}
// if no non-legal character was found, return true
return true;
}
Although there might be a better alternative using the standard libraries, especially if you need to compare very long strings with a large set of legal characters.
Upvotes: 0