필터 지우기
필터 지우기

using strcmpi in switch case

조회 수: 3 (최근 30일)
Natalie Huynh
Natalie Huynh 2019년 9월 30일
편집: Natalie Huynh 2019년 9월 30일
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

채택된 답변

meghannmarie
meghannmarie 2019년 9월 30일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by