How do I use characters with an if statement?
87 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Jan
2020-11-3
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 个评论
更多回答(1 个)
Adam Danz
2020-11-3
编辑:Adam Danz
2020-11-3
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 个评论
Adam Danz
2020-11-3
@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....
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!