I read a string from the console. How do I make sure it only contains English characters and digits?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Assuming that by “English characters” you are simply referring to the 26-character Latin alphabet, this would be an area where I would use regular expressions:
^[a-zA-Z0-9 ]*$For example:
The benefit of regular expressions in this case is that all you really care about is whether or not a string matches a pattern – this is one where regular expressions work wonderfully. It clearly captures your intent, and it’s easy to extend if you definition of “English characters” expands beyond just the 26 alphabetic ones.
There’s a decent series of articles here that teach more about regular expressions.
Jørn Schou-Rode’s answer provides a great explanation of how the regular expression presented here works to match your input.