How do I use characters with an if statement?
81 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
John Jamieson
el 3 de Nov. de 2020
Comentada: Adam Danz
el 1 de Sept. de 2021
My code looks like this
Prompt='Please press any key to roll the dice, press Q or q to quit program: ';
str=input(Prompt, 's');
if str == q||Q
fprintf('program terminated')
end
end
Essentially what I want to do is if the user inputs Q, the fprintf statement is true. However, I'm unsure of how to do this, as it only see's q as an unrecognized value
0 comentarios
Respuesta aceptada
Jan
el 3 de Nov. de 2020
Prompt = 'Please press any key to roll the dice, press Q or q to quit program: ';
str = input(Prompt, 's');
if strncmpi(str, 'q', 1)
fprintf('program terminated')
end
strncmpi compares the given number of characters ignoring the case. This is nicer than:
if ~isempty(str) && str(1) == 'q' || str(1) == 'Q'
or
if ~isempty(str) && lower(str(1)) == 'q'
2 comentarios
Más respuestas (1)
Adam Danz
el 3 de Nov. de 2020
Editada: Adam Danz
el 3 de Nov. de 2020
If you want to consider case (assuming str, q, and Q are all strings or character arrays)
if any(strcmp(str, {q,Q})) % [q,Q] for string arrays
or
if ismember(str, {q,Q}) % [q,Q] for string arrays
If you want to ignore case
if any(strcmpi(str, {q,Q})) % [q,Q] for string arrays
or
if ismember(lower(str), lower({q,Q})) % [q,Q] for string arrays
2 comentarios
Adam Danz
el 3 de Nov. de 2020
@John Jamieson In that case (see Rik's comment above), {q,Q} would be {'q','Q'} or ["q","Q"] for strings.
Also, just a public service announcement, when using input() you should include input validation. For example,
if you're expecting a single character,
assert(numel(str)==1, 'Input must be 1 character.')
if you're expecting a word with no spaces,
assert(any(isspace(str)), 'Input must not contain spaces.')
if you're expecting only letters and no numbers,
assert(all(isletter(str)),'Input must only be letters')
etc....
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!