using string in if statement

771 ビュー (過去 30 日間)
Oyewale Oyelami
Oyewale Oyelami 2011 年 7 月 18 日
回答済み: karipuff 2021 年 10 月 29 日
i want to use string in my if boolean expression....something like if(name =='daniel') disp...... All i have been getting are errors...is it possible and if yes how? Thanks

回答 (3 件)

Walter Roberson
Walter Roberson 2011 年 7 月 18 日
If you attempt to compare two strings using == and the strings are not the same length, then you will get errors. == can be used for strings only if they are the same length.
Use strcmp() or isequal() or strcmpi().
  2 件のコメント
N/A
N/A 2019 年 3 月 26 日
What if I'm using an if statement where I want the if condition to be met if the string being compared has only a part of the actual string
How do I make that work?
example
button = buttons
if button ==contains(str, "butt")
run()
else
stop()
end
Steven Lord
Steven Lord 2019 年 3 月 26 日
Working with a string array is different than working with a char array. What Walter wrote is true for char arrays (which was the main data type for storing text data in 2011, as the string class didn't exist yet.)
button = "button";
str = 'abcde';
if contains(str, button)
disp("[" + str + "] contains the string [" + button + "]")
else
disp("[" + str + "] doesn't contain the string [" + button + "]")
end
Now change the contents of the str variable and perform the same comparison.
str = 'space button';
if contains(str, button)
disp("[" + str + "] contains the string [" + button + "]")
else
disp("[" + str + "] doesn't contain the string [" + button + "]")
end
The contains function can accept two char vectors, two string arrays, two cell arrays containing char vectors, or a combination of those three types.

サインインしてコメントする。


Fangjun Jiang
Fangjun Jiang 2011 年 7 月 18 日
The following code should work. You can also use isequal(MyName,'Daniel'), strcmp(), strcmpi() etc.
MyName='Daniel';
if MyName=='Daniel'
disp('correct name');
else
disp('wrong name')
end
  2 件のコメント
Jan
Jan 2011 年 7 月 18 日
But this will *not* work: "MyName = 'Daniela'; if MyName == 'Daniel', ...", because the arrays compared by == must have the same size or one is a scalar.
Fangjun Jiang
Fangjun Jiang 2011 年 7 月 18 日
Now I understand why the OP had errors. I personally never use == to compare strings. The error message should be pretty clear though, right?

サインインしてコメントする。


karipuff
karipuff 2021 年 10 月 29 日
str = 'abc'
if strcmp('abc',str)
expression
else
expression
end

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by