How to confirm user input is a word based on ascii table?
Show older comments
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)
James Tursa
on 29 Nov 2016
Like this?
prompt = 'Enter word ';
while( true )
answer = input(prompt, 's');
if( all(ismember(answer,'ABCDEFGHIJKLMNOPQRSTUVWXYZ')) )
break;
end
end
6 Comments
Maureen O'Brien
on 30 Nov 2016
James Tursa
on 30 Nov 2016
Edited: James Tursa
on 30 Nov 2016
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.
Walter Roberson
on 30 Nov 2016
if( all(ismember(answer, 65:90)) )
James Tursa
on 30 Nov 2016
Edited: James Tursa
on 30 Nov 2016
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.
Walter Roberson
on 30 Nov 2016
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.
Maureen O'Brien
on 30 Nov 2016
Categories
Find more on Tables in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!