Switch Case where case is a word_anynumber
Ältere Kommentare anzeigen
I am trying to make a switch case where the case is satisfied by the following:
word_anynumber (ie word_1 or word_2 etc)
what do i do to achieve this?
The issue is that i want the case to do the same thing for any case with word_#, but i don't want to create cases for each number because i have a variable number of numbers each time this script runs.
Any help would be greatly appreciated.
-Jonathan
Akzeptierte Antwort
Weitere Antworten (2)
Fangjun Jiang
am 14 Nov. 2011
0 Stimmen
Use strfind(), strcmp() or strmatch(). You may also consider use "if-else" rather than 'case-switch"
if strfind(StrVariable,'word_')
1 Kommentar
Daniel Shub
am 15 Nov. 2011
I think this will evaluate to true if StrVariable is of the form * word_*. It doesn't require word to be the first element, numbers to follow the underscore, or the numbers to be the final elements.
Jonathan
am 14 Nov. 2011
If all of your cases are similar to what you describe, then you can use strtok like this.
a = 'word_4';
b = 'word_27';
c = 'byte_3';
d = 'bit_14';
switchStr = a;
switch strtok(switchStr, '_')
case 'word'
disp('word')
case 'byte'
disp('byte')
case 'bit'
disp('bit')
otherwise
disp('otherwise')
end
This displays 'word'. Try repeating this with switchStr set to b, c, and d.
6 Kommentare
Jonathan Crider
am 15 Nov. 2011
bym
am 15 Nov. 2011
how many numbers do you wish to distinguish? 1-10, 1-255,1-inf ?
Jonathan Crider
am 15 Nov. 2011
Jonathan Crider
am 15 Nov. 2011
Jonathan
am 15 Nov. 2011
strtok does work in this case since "strtok('apple', '_')" returns the string "apple".
Jonathan
am 15 Nov. 2011
a = 'apple';
b = 'orange';
c = 'banana';
d = 'grape_1';
e = 'grape_2';
f = 'grape_3';
switchStr = d; % goes through a through f
switch strtok(switchStr, '_')
case 'apple'
disp('apple')
case 'orange'
disp('orange')
case 'banana'
disp('banana')
case 'grape' % this is where i have a problem
disp('grapes')
end
Kategorien
Mehr zu Characters and Strings finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!