How to confirm user input is a word based on ascii table?

I'm trying to figure out how to confirm that answer(listed below) is a word based on the ASCII table. I've thought about trying a while loop with the char to say continue while answer equals ASCII value 65-90. Below is two lines of my code. Thanks
prompt = 'Enter word', 's';
answer = input(prompt, 's');

Answers (1)

Like this?
prompt = 'Enter word ';
while( true )
answer = input(prompt, 's');
if( all(ismember(answer,'ABCDEFGHIJKLMNOPQRSTUVWXYZ')) )
break;
end
end

6 Comments

I think what I'm trying to do, if it's possible, is convert the letters in the word to their ASCII values and then make sure that the ASCII values are letters. Thank you for your help so far
The code above makes sure all of the characters in the variable "answer" are capital letters (i.e., from the set AB...Z). That looks like what you were trying to do. There is no need to convert back & forth between ASCII numbers for this check. If you want to allow lower case letters also, just add the characters ab...z to the allowed list.
Well, yes, 65:90 is more succinct. But I was trying to avoid assumed ASCII coding to steer OP away from thinking that was a requirement to accomplish the task.
Also valid:
if all(ismember(answer,'A':'Z'))
and
if all(ismember(answer+0, 65:90))
This works most directly as the user was imagining, converting the input to position numbers and comparing them to the desired positions. But it is not necessary.
And as soon as you start talking about ASCII values, you have to start worrying about translating from MATLAB characters into ASCII,
ANSII_answer = unicode2native(answer,'ASCII');
This will give numeric values. The characters that were non-ASCII will be translated to the value 26.
Thank you for all of your help. It is much appreciated

Sign in to comment.

Categories

Asked:

on 29 Nov 2016

Commented:

on 30 Nov 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!