If statement comparing strings

58 次查看(过去 30 天)
Sam Falzone
Sam Falzone 2011-4-5
I want to do this:
if 'Word1' == 'Word2' 'do something' end
'Word1' and 'Word2' aren't necessarily going to be the same amount of characters.
Everything I try ends in "eq error".
How do I do this?

回答(1 个)

Walter Roberson
Walter Roberson 2011-4-5
编辑:Walter Roberson 2017-11-28
strcmp('Word1', 'Word2')
OR
all(size('Word1') == size('Word2')) && all('Word1' == 'Word2')
OR
isequal('Word1', 'Word2')
  2 个评论
Zhuoying Lin
Zhuoying Lin 2017-11-28
编辑:Walter Roberson 2017-11-28
Hi I have a similar question. I type:
if isequal(x,'a') && isequal(x,'p') && isequal(x,'T')==0
fprintf('ERROR:You entered incorrect choice.')
but it doesn't work
Walter Roberson
Walter Roberson 2017-11-28
if ~ismember(x, {'a', 'p', 'T'))
printf('ERROR:You entered incorrect choice.');
end
or
if ~(isequal(x, 'a') || isequal(x, 'p') || isequal(x, 'T'))
fprintf('ERROR:You entered incorrect choice.');
end
or
if ~(strcmp(x, 'a') || strcmp(x, 'p') || strcmp(x, 'T'))
fprintf('ERROR:You entered incorrect choice.');
end
or
if ~strcmp(x, 'a') && ~strcmp(x, 'p') && ~strcmp(x, 'T')
fprintf('ERROR:You entered incorrect choice.');
end
or
if ~any([strcmp(x, 'a'), strcmp(x, 'p'), strcmp(x, 'T')])
fprintf('ERROR:You entered incorrect choice.');
end

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by