how to compare string?

1 Ansicht (letzte 30 Tage)
SRIGUHAN MURUGASUNDARAM
SRIGUHAN MURUGASUNDARAM am 18 Jan. 2018
Kommentiert: Steven Lord am 28 Feb. 2018
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?

Akzeptierte Antwort

Birdman
Birdman am 18 Jan. 2018
Bearbeitet: Birdman am 18 Jan. 2018
Try this:
fuel=input('select the gaseous component CH4,ethane,propane,butane,H2,CO,CO2,N2\n');
if prod(ismember(fuel,'CH4'))
density=0.716; %kg/m^
LCV=35.83; %MJ/m^3
cc=1; hh=4; oo=0; nn=0;
TMmass=cc+hh+oo+hh;
disp('total mass of CH4');
disp(TMmass);
end
if prod(ismember(fuel,'ethane'))
density=1.342; %kg/m^3
disp(density);
LCV=63.76; %MJ/m^3
disp(LCV);
cc=2;
disp(cc);
hh=6;
disp(hh);
oo=0;
disp(oo);
nn=0;
disp(nn);
TMmass=cc+hh+oo+hh;
disp('total mass of CH4');
disp(TMmass);
end
Do not forget to enter your input in char form. Like
>>'CH4'
or
>>'ethane'
  5 Kommentare
Stephen23
Stephen23 am 18 Jan. 2018
Bearbeitet: Stephen23 am 18 Jan. 2018
This is a buggy way to compare strings. It will work incorrectly even if the order of the characters is different, or if any characters are repeated. Avoid using this code.
Strings should be compared simply using strcmp and strcmpi. See the other answers for simpler and much more robust code.
Birdman
Birdman am 18 Jan. 2018
Yes, thank you for attention.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

Steven Lord
Steven Lord am 18 Jan. 2018
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 Kommentare
SRIGUHAN MURUGASUNDARAM
SRIGUHAN MURUGASUNDARAM am 27 Feb. 2018
Hi Mr.Steven Lord, your help was really usefull. i have some doubts in my mathwork. can you please help me ? if you dont mind... may i know how to contact you? email or any chat..
Steven Lord
Steven Lord am 28 Feb. 2018
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.

Melden Sie sich an, um zu kommentieren.


Guillaume
Guillaume am 18 Jan. 2018
string comparisons are done with strcmp, or strcmpi for case insensitive. Never with ==

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by