how to compare string?
古いコメントを表示
i want to take input fuel=CH4 or CO or Co2, %its num + string input if fuel==CH4 % if fuel is CH4 i need to fix some value for variable %if fuel is Co or Co2 i need to fix some value can you please help me how to do it?
採用された回答
その他の回答 (2 件)
Steven Lord
2018 年 1 月 18 日
The approach Birdman suggested won't work if the user enters more characters than you expected.
fuel = 'CH4CC4'
prod(ismember(fuel, 'CH4')) % returns 1
It also won't work if the user enters lower-case characters when you expected upper-case.
prod(ismember('ch4', 'CH4')) % returns 0
Use isequal, strcmp, strcmpi, or a switch / case statement. To handle case matching, you might also want to use upper or lower to convert the input into a consistent case.
isequal(fuel, 'CH4') % false
strcmp(fuel, 'CH4') % false
switch fuel
case 'CH4'
result = true
otherwise
result = false
end
3 件のコメント
SRIGUHAN MURUGASUNDARAM
2018 年 1 月 18 日
SRIGUHAN MURUGASUNDARAM
2018 年 2 月 27 日
Steven Lord
2018 年 2 月 28 日
Please use the Ask button at the top of the page to ask a new question. That way I can read it and so can others who may respond before I can.
Guillaume
2018 年 1 月 18 日
2 投票
カテゴリ
ヘルプ センター および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!