Filter löschen
Filter löschen

using strcmpi in switch case

3 Ansichten (letzte 30 Tage)
Natalie Huynh
Natalie Huynh am 30 Sep. 2019
Bearbeitet: Natalie Huynh am 30 Sep. 2019
I was able to do this using with an if-else statement (as shown below), but am unsure of how to convert it to a switch case. I know that I could put every single permutation of each case name in an array, but I wanted to know if there was an easier way to do that.
function state = stateAbbreviation(inputStr)
origState = upper(inputStr);
alabamaStr = 'Alabama';
alabamaAbrev = 'AL';
alaskaStr = 'Alaska';
alaskaAbrev = 'AK';
arizonaStr = 'Arizona';
arizonaAbrev = 'AZ';
kansasStr = 'Kansas';
kansasAbrev = 'KS';
caliStr = 'California';
caliAbrev = 'CA';
if strcmpi(origState, alabamaStr)
state = "AL";
elseif strcmpi(origState, alabamaAbrev)
state = "Alabama";
elseif strcmpi(origState, alaskaStr)
state = "AK";
elseif strcmpi(origState, alaskaAbrev)
state = "Alaska";
elseif strcmpi(origState, arizonaStr)
state = "AZ";
elseif strcmpi(origState, arizonaAbrev)
state = "Arizona";
elseif strcmpi(origState, kansasStr)
state = "KS";
elseif strcmpi(origState, kansasAbrev)
state = "Kansas";
elseif strcmpi(origState, caliStr)
state = "CA";
elseif strcmpi(origState, caliAbrev)
state = "California";
else
disp('Unknown')
end
end

Akzeptierte Antwort

meghannmarie
meghannmarie am 30 Sep. 2019
For a switch statement try this:
function state = stateAbbreviation(inputStr)
switch upper(inputStr)
case 'ALASKA'
state = 'AK';
case 'AK'
state = 'Alaska';
case 'ALABAMA'
state = 'AL';
case 'AL'
state = 'Alabama';
otherwise
disp('Unknown State')
end
end

Weitere Antworten (0)

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