Let's say I have two strings (string1, string2) based off of user inputs. I want string1 to be at least 5 characters, at most 10 characters, and only allowed to contain the following:
- Upper case letters
- Lower case letters
- Numbers (0-9)
Otherwise, the user will be prompted to keep entering strings until the requirements are met.
while(len(string1)<5 or len(string1)>10) {
if(len(string1) > 10) {
cout << "Please enter a string that is less than 10 characters: ";
cin >> input;
} else if(len(string) < 5) {
cout << "Please enter a string that is more than 5 characters: ";
cin >> input;
} else {
cout << "Please enter a string with legal characters (uppercase/lowercase letters and numbers): ";
cin >> input;
}
How would I check if string1 only contains uppercase letters, lowercase letters, and numbers? Would I use the following in some sort of way?…
string legalChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
string1.find_first_not_of(legalChars)
As for string2, I want the user input to be at least 6 characters long and to contain at least one non-letter character.
while(len(string2)<6) {
if(len(string2)<6) {
cout << "Please enter a string that is at least 6 characters long: ";
cin >> input2;
}
}
How would I check for non-letter characters in string2? How should I approach this problem?
Best Answer
For
string1
you can simply check for the length to be at least 5 characters and at most 10 characters (usestd::string::length
), and pass each character intoisalnum
to check if it is alphanumeric.For
string2
you can check that it's at least 6 characters long and has at least one uppercase letter by usingisupper
.Or as @Lorehead pointed out, you can just use regex. Which is better is entirely up to you.